"Method cannot be translated into a store expression" 奇怪的行为

"Method cannot be translated into a store expression" weird behavior

我有这两个具有一对多关系的模型:

[Table("User")]
public class User
{
    public User()
    {
        Times = new HashSet<Time>();
    }

    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public Guid Guid { get; set; }

    public virtual ICollection<Time> Times { get; set; }
}

[Table("Time")]
public class Time
{
    [Key]
    public long TimeId { get; set; }
    public DateTime WorkDay { get; set; }
    public Guid UserGuid { get; set; }
    public virtual User User { get; set; }
}

和上下文中的方法 class 其中 returns DataTable。 查询通过 .ToDataTable() 扩展(或 .ToList() 或其他)后,第一次实施失败 有例外:

LINQ to Entities does not recognize the method 'System.String ToShortDateString()' method, and this method cannot be translated into a store expression

第二个非常好。 问题是为什么?

第一次实施。没用

public DataTable GetDtProjectsForUser(User user)
{
    var query = from time in Time
                select new
                {
                    WorkDay = time.WorkDay.ToShortDateString(),
                };
    return query.ToDataTable();
}

第二个。它确实有效

public DataTable GetDtProjectsForUser(User user)
{
    var localUser = User.Find(user.Guid);
    var query = from time in localUser.Times
                select new
                {
                    WorkDay = time.WorkDay.ToShortDateString(),
                };
    return query.ToDataTable();
}

Linq 是一种延迟执行。在您的第一个代码中,时间变量未存储在内存中,而在第二个代码中,您已将集合存储在 localUser 变量中。
您可以在 Charlie Calvert's Community Blog 阅读有关 linq 和延迟执行的更多信息。

Rohit 的回答或多或少是正确的,但他在评论中的解释是错误的。

localUser.Times(大概)是一个 ICollection<Time>。构建 ICollection 需要枚举结果集。引用集合后立即执行查询。您的查询相当于:

var collection = localUser.Times.Select(t => new { WorkDay = t.WorkDay.ToShortDateString() });

一旦执行 localUser.Times,就会对数据库进行查询并加载 Times 集合。随后的 .Select() 是 LINQ to Objects 查询。