2013-03-13 50 views
1

我正在使用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); 
     } 

    } 
} 

我得到的错误:

The specified type member 'FullName' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

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

回答

2

的问题是在SELECT子句的初始化表达式:

CreatedBy = i.Action.CreatedBy.FullName 

这是导致Linq到实体供应商,试图找到一个名为“全名”属性的映射。这同样适用于如果您尝试使用扩展方法。

你可以尽管这样做:

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通过自定义属性来访问名字