不允许在查询中显式构造实体类型

错误原因:

1     from f in context.TableName
2     select new MyModel()
3     {
4         Id = f.Id
5     };

select new语句中如果指定linq自动生成的实体类并且实体类中有实体类对象,就会产生错误

用以下的代码可解决:

方法一:

注意:select new的是匿名实体,只能用匿名实体,后面代码会转换回相应实体

 

 1 IQueryable query = from f in context.TableName
 2                                        join c in context.tableName_2
 3                                        on f.NutrientId equals c.Id
 4                                        where f.ContentId == ContentId
 5                                        select new
 6                                        {
 7                                            Id = f.Id,
 8                                            ContentId = f.ContentId,
 9                                            NutrientId = f.NutrientId,
10                                            OrderValue = f.OrderValue,
11                                            ContainNum = f.ContainNum,
12                                            Remark = f.Remark
13                                        };
14                     using (context.Connection)
15                    {
16                         DbCommand command = context.GetCommand(query);
17                         if (context.Connection.State == ConnectionState.Closed)
18                         {
19                             context.Connection.Open();
20                         }
21                         using (DbDataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection))
22                         {
23                             result = context.Translate<MyModel>(reader).ToList();
24                         }
25                     }

 

方法二:

自定义实体类,属性CookBookAttr是实体类对象,是可行的

 1 IList<FoodMaterialNutrient> aa = (from f in context.tablename_1
 2                               join c in context.tablename_2 on f.NutrientId equals c.Id
 3                               where f.ContentId == ContentId
 4                               select new MyModel()
 5                               {
 6                                   Id = f.Id,
 7                                   OrderValue = f.OrderValue,
 8                                   Remark = f.Remark,
 9                                   ContainNum = f.ContainNum,
10                                   AttributeName = c.AttributeName,
11                                   Unit = c.Unit,
12                                   CookBookAttr = c
13                               }).ToList();
posted @ 2012-09-18 10:00  鸿bi  阅读(537)  评论(0编辑  收藏  举报