支持Linq To Entities的唯一原始类型或枚举类型'错误

duy*_*yen 7 linq linq-to-entities linq-to-sql c#-4.0 entity-framework-5

我正在使用LinqPad来测试我的查询.当LInqPad连接到我的数据库(LInq to SQL)时,此查询有效但当我更改连接以使用我的Entity Framework 5 Model.dll时它不起作用.(Linq to Entity).这是在C#中.

我有两个名为Plan和PlanDetails的表.关系是许多PlanDetails的一个计划.

var q = from pd in PlanDetails
        select new {
            pd.PlanDetailID,
            ThePlanName = (from p in this.Plans
                    where p.PlanID == pd.PlanID
                    select p.PlanName)
        };
var results = q.ToList();
q.Dump(); //This is a linqpad method to output the result.
Run Code Online (Sandbox Code Playgroud)

我收到此错误"NotSupportedException:无法创建类型'Domain.Data.Plan'的常量值.在此上下文中仅支持基本类型或枚举类型." 任何想法为什么这只适用于Linq to SQL?

Man*_*hra 17

基本上它意味着您在查询中使用一些复杂的数据类型进行比较.在你的情况下,我怀疑from p in this.Plans where p.PlanID == pd.PlanID是罪魁祸首.

它取决于DataProvider.它可能适用于Sql Data Provider,但不适用于SqlCE数据提供程序等.

你应该做的是将你的this.Plans集合转换为只包含Ids的原始类型集合

var integers = PlanDetails.Plans.Select(s=>s.Id).ToList();
Run Code Online (Sandbox Code Playgroud)

然后在里面使用这个列表.

var q = from pd in PlanDetails
        select new {
            pd.PlanDetailID,
            ThePlanName = (from p in integers
                    where p == pd.PlanID
                    select pd.PlanName)
        };
Run Code Online (Sandbox Code Playgroud)

  • 我担心为什么他需要做一个嵌套查询,当他说一个计划到多个PlanDetails ...这意味着PlanDetails不能独立......他们必须与计划有关...所以如果你有一个PlanDetail它应该有一个名为Plan的Navigational属性(如果没有重命名) (3认同)

Ram*_*Ram 5

当我尝试对实体框架表达式中的导航属性进行空检查时出现此错误

我通过不在表达式中使用非空检查而仅使用 Any() 函数来解决它。

  protected Expression<Func<Entities.Employee, bool>> BriefShouldAppearInSearchResults(
        IQueryable<Entities.Employee> briefs, string username)
    {
       var trimmedUsername = NameHelper.GetFormattedName(username);

        Expression<Func<Entities.Employee, bool>> filterExpression = cse =>                
             cse.Employee.Cars.All(c => 
                 c.Employee.Cars!=null &&  <--Removing this line resolved my issue
                 c.Employee.Cars.Any(cur => cur.CarMake =="Benz")));

        return filterExpression;
    }
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助某人!