简体   繁体   English

EF:将数据投影到类的子类中

[英]EF : Projecting data into a sub-class of a class

I'm trying to project some data into a list of POCOs where the POCO contains an instance of another type of POCO. 我正在尝试将一些数据投影到POCO列表中,其中POCO包含另一种类型的POCO的实例。

The two classes are Case and MyEntity, where Case has an instance of MyEntity called Client. 这两个类是Case和MyEntity,其中Case有一个名为Client的MyEntity实例。

public class Case
{
    public int ID { get; set; }
    public string CaseReference { get; set; }
    public bool Deleted { get; set; }
    public MyEntity Client { get; set; }
}

and

public class MyEntity
{
    public int ID { get; set; }
    public string Name { get; set; }
}

I'm trying to query it like this but it's failing reporting "Unable to create a constant value of type MyEntity": 我试图像这样查询它,但它报告失败“无法创建MyEntity类型的常量值”:

 var result = (from c in context.cases
               where c.case_ref.Contains(caseReference)
               select new Case
               {                                      
                   ID = c.id,
                   CaseReference = c.case_ref,
                   Deleted = c.deleted,
                   Client = new MyEntity { ID = c.client.id, Name = c.client.name } 
               }).ToList();

What's the best way of doing this, am I going to have to break it down into separate queries? 这样做的最佳方式是什么,我是否必须将其分解为单独的查询?

Entity Framework's IQueryable implementation is more picky about creating new objects in objects than regular linq to objects ( IEnumerable ). 实体框架的IQueryable实现在对象中创建新对象比在常规linq到对象( IEnumerable )中更加挑剔。 If you first convert your query result to IEnumerable by ToList(): 如果您首先通过ToList()将查询结果转换为IEnumerable

context.cases.Where(c => c.case_ref.Contains(caseReference).ToList()

Then you can continue creating new Case objects the way you want. 然后,您可以按照自己的方式继续创建new Case对象。 (You may need to Include() Case.Client in context.cases ). (您可能需要在context.cases Include() Case.Client)。

Following on from Gert's answer, I thought I'd post the answer in Query Expression syntax for anyone else having this problem. 继Gert的回答之后,我想我会在查询表达式语法中为有这个问题的其他人发布答案。

Note that I had to add a bit of checking to handle there being no data in the client table: 请注意,我必须添加一些检查来处理客户端表中没有数据:

var result = (from c2 in ((from c1 in context.cases
                           where c1.case_ref.Contains(caseReference)
                           select c1).ToList())
              select new Case
              {
                  ID = c2.id,
                  CaseReference = c2.case_ref,
                  Deleted = c2.deleted,
                  Client = (c2.client_id != null ? new MyEntity { ID = c2.client.ID, Name = c2.client.name } : null)
              }).ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM