如何使用 linq将字符串转换为日期时间到实体…. 我有以下查询,其中visit_date列数据类型是字符串… var memberl = from v in abc.visits join m in abc.members on v.member_Id equals m.member_Id where Convert.ToDat
我有以下查询,其中visit_date列数据类型是字符串…
var memberl = from v in abc.visits join m in abc.members on v.member_Id equals m.member_Id where Convert.ToDateTime(v.visit_Date) >= startdate && Convert.ToDateTime(v.visit_Date) <= enddate group m by new { m.member_Firstname, m.member_Lastname, m.member_Id } into g orderby g.Count() select new { numVisits = g.Count(), firstname = g.Key.member_Firstname, lastname = g.Key.member_Lastname };
不幸的是我无法改变架构……
我有错误:
linq to entites does not recognise Convert.ToDatetime method
是否有任何可能的解决方案将字符串转换为Datetime?
更新的代码:
根据要求我更新了我的问题
var data = (from v in abc.visits join m in abc.members on v.member_Id equals m.member_Id select new { MemberID = v.member_Id, VisiteDate = v.visit_Date, FirstName = m.member_Firstname, LastName = m.member_Lastname }).ToList(); var membersdata = from d in data where Convert.ToDateTime(d.VisiteDate) >= startdate && Convert.ToDateTime(d.VisiteDate) <= enddate group m by new { d.FirstName, d.LastName, d.MemberID } into g orderby g.Count() select new { numVisits = g.Count(), firstname = g.Key.FirstName, lastname = g.Key.LastName };我不认为EF支持将String转换为DateTime或反之亦然.
在我看来,你有两个选择,取决于字符串字段中日期的格式:
如果格式非常简单,那么字符串比较可能就足够了:
// Convert the boundaries to strings first // TODO: Set the ToString format option to match the database format string startDateAsString = startdate.ToString("yyyyMMdd"); string endDateAsString = enddate.ToString("yyyyMMdd"); // Query based on string comparison var memberl = from v in abc.visits join m in abc.members on v.member_Id equals m.member_Id where v.visit_Date.CompareTo(startDateAsString) >= 0 && v.visit_Date.CompareTo(endDateAsString) <= 0 group m by new { m.member_Firstname, m.member_Lastname, m.member_Id } into g orderby g.Count() select new { numVisits = g.Count(), firstname = g.Key.member_Firstname, lastname = g.Key.member_Lastname };
如果日期的字符串表示形式更复杂,并且简单的字符串比较无法提供帮助,您可以考虑在访问表上创建一个视图,该视图在数据库级别为您进行转换:
CREATE VIEW VisitsWithDate (MemberId, VisitDate) AS SELECT MemberId, Convert(datetime, VisitDate, 112) -- For instance FROM Visits
然后将此视图导入DataModel.您可能需要做一些魔术才能使关系发挥作用.
希望能帮助到你.