【问题标题】:Keep Entity Framework From Executing Properties or Extension Methods阻止实体框架执行属性或扩展方法
【发布时间】:2013-03-13 23:10:22
【问题描述】:

我正在使用 EF5 Code First 模型。考虑以下实体框架查询:

var results = from i in context.Table1
            where i.ID == Id // passed in
            select new TableInfo()
            {
                Name = i.Name,
                ActionDate = i.Action.ActionDate,
                CreatedDate = i.Action.CreatedDate,
                CreatedBy = i.Action.CreatedBy.FullName
            };

FullName 属性是这样定义的:

[NotMapped]
[Display(Name = "Full Name")]
public string FullName
{
    get
    {
        string ret = string.Empty;
        if (String.IsNullOrEmpty(LAST_NAME) || String.IsNullOrEmpty(FIRST_NAME))
        {
            return "";
        }
        else
        {
            return string.Format("{0}, {1}", LAST_NAME, FIRST_NAME);
        }

    }
}

我得到错误:

LINQ to Entities 不支持指定的类型成员“FullName”。仅支持初始化器、实体成员和实体导航属性。

如果我创建一个扩展方法来做同样的事情,我会得到类似的错误。所以问题是如何防止 EF 尝试在数据存储上运行这些东西?

【问题讨论】:

    标签: linq entity-framework-5


    【解决方案1】:

    问题是select子句的初始化器中的表达式:

    CreatedBy = i.Action.CreatedBy.FullName
    

    这导致 Linq-to-Entity 提供程序尝试为名为“FullName”的属性查找映射。如果您尝试使用扩展方法,这同样适用。

    你可以这样做:

    var results = 
        from i in context.Table1
        where i.ID == Id // passed in
        select new TableInfo()
        {
            Name = i.Name,
            ActionDate = i.Action.ActionDate,
            CreatedDate = i.Action.CreatedDate,
            CreatedBy = i.Action.CreatedBy
        };
    

    然后使用item.CreatedBy.FullName 通过您的自定义属性访问名称

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-03-12
      • 2016-07-29
      • 1970-01-01
      • 2021-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多