【问题标题】:Entity Framework error: Unable to create a constant value of type '..'. Only primitive types实体框架错误:无法创建类型为“..”的常量值。只有原始类型
【发布时间】:2012-01-05 23:33:57
【问题描述】:

我正在使用 EF4。我正在尝试将 SQL 转换为 LINQ 到 EF,但出现错误。我希望 EF 在数据库中创建和执行 SQL(而不是在内存中做事)。比较使用的是整数的原始类型。如何修复错误。我正在考虑使用 now group into 语法。

SQL:

SELECT   Restaurant.RestaurantID
         ,CASE  WHEN FoodType.FoodTypeID IS NULL THEN NULL ELSE CustRating.Rating END AS Rating
 FROM               Restaurant Restaurant
 LEFT OUTER JOIN    CustRating CustRating 
 ON                 Restaurant.RestaurantID =   CustRating.RestaurantID
 LEFT OUTER JOIN    FoodType FoodType 
 ON                 FoodType.FoodTypeID = CustRating.FoodTypeID
 AND        FoodType.FoodTypeName = 'Taco'

LINQ:(在 LinqPad 中测试)

var query =
        from restaurant in Restaurants
        from customerRating
        in CustomerRatings
            .Where( cr => cr.RestaurantID == restaurant.RestaurantID)
        .DefaultIfEmpty()

        from foodType
        in FoodTypes
      .Where(ft => ft.FoodTypeID == customerRating.FoodTypeID && ft.FoodTypeName == "Taco")
                      .DefaultIfEmpty()
        select restaurant;                  
           query.Dump();

错误信息:

Unable to create a constant value of type 'CustomerRating'. 
Only primitive types ('such as Int32, String, and Guid') are supported in this context.

【问题讨论】:

    标签: c# .net entity-framework linq-to-entities


    【解决方案1】:

    我继续使用 join into 解决方案。我仍然对为什么我得到其他样式的错误感兴趣。

    var query = from restaurant in Restaurants
    join cr in CustomerRatings on restaurant.RestaurantID equals cr.RestaurantID
    into children
    from child in children.DefaultIfEmpty()
    join foodType in FoodTypes
    on  child.FoodTypeID equals foodType.FoodTypeID   
    into children2
    from child2 in children2.Where(ft => ft.FoodTypeName == "Taco").DefaultIfEmpty()
    
    select new { RestaurantID = restaurant.RestaurantID, 
    FoodTypeID = (int?) child2.FoodTypeID,
    
    Rating = ( (int?) child2.FoodTypeID == null?  0 : (int?)child.Rating )
    
    }; 
    
    query.Dump();
    

    【讨论】:

    • 您最初的方法是错误的。这不是您预期的查询。即使它会工作,你也会得到两个交叉连接的查询。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多