如何在linq中使用TimeZoneInfo.ConvertTimeFromUtc来实现sql?

时间:2014-01-20 14:03:49

标签: c# sql linq datacontext

我有一个名为zeekuser的用户表,我在其中存储与用户相关的时区信息。在使用下面的代码检索我时,

var v = (from s in dc.UserWebSites
                             join zk in dc.ZeekUsers on s.aspnet_User.UserId equals zk.UserId
                             where s.aspnet_User.LoweredUserName.Equals(strUsername.ToLower())
                             select new UserWebSiteInfo
                             {
                                 CreateDt = TimeZoneInfo.ConvertTimeFromUtc(s.CreateDt, TimeZoneInfo.FindSystemTimeZoneById(zk.TimeZoneID)),
                                 LastUpdateDt = TimeZoneInfo.ConvertTimeFromUtc(s.LastUpdate, TimeZoneInfo.FindSystemTimeZoneById(zk.TimeZoneID)),
                                 LogoImage = s.LogoImage,
                                 Nickname = s.Nickname,
                                 Title1 = s.Title1,
                                 Title2 = s.Title2,
                                 SiteID = s.SiteID.ToString(),
                                 TemplateID = s.TemplateID.ToString(),
                                 TemplateName = s.WebSiteTemplate.ThemeName,
                                 IsActive = s.IsActive,
                                 IsRedirect = s.IsRedirect,
                                 RedirectURL = s.RedirectURL,
                                 UPID = s.UPID.ToString(),
                                 UserId = s.aspnet_User.UserId.ToString(),
                                 Username = s.aspnet_User.UserName,
                                 UserProductName = s.UserProductDetail.Nickname,
                                 PageCount = s.UserWebSitePages.Count(),
                                 AuthorName = s.AuthorName,
                                 AuthorURL = s.AuthorURL
                             }).OrderByDescending(y => y.LastUpdateDt);
                    info = v.ToList();

但我收到的错误

方法'System.TimeZoneInfo FindSystemTimeZoneById(System.String)'没有支持的SQL转换。

每个不同的用户可以拥有不同的时区。我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

我怀疑您是否可以在发送到SQL Server的查询中执行此操作。相反,使用AsEnumerable更改上下文以在.NET端执行最后一步:

var query = from s in dc.UserWebSites
            join zk in dc.ZeekUsers on s.aspnet_User.UserId equals zk.UserId
            where s.aspnet_User.LoweredUserName.Equals(strUsername.ToLower())
            orderby s.LastUpdate descending
            select new { Site = s, ZoneId = zk.TimeZoneID };

// Do the rest of the query in-process, so we can use time zones.
var results = (from pair in query.AsEnumerable()
               let site = pair.Site
               let zone = TimeZoneInfo.FindSystemTimeZoneById(pair.ZoneId)
               select new UserWebSiteInfo {
                   // Select all your properties here
               }).ToList();

这假设UserWebSites中的信息不会超过你用于构建UserWebSiteInfo的信息。如果 是一堆无关紧要的信息,您应该在初始数据库端查询中明确选择相关部分。