[英]Left outer join in Linq To Entities (The entity or complex type cannot be constructed in a LINQ to Entities query.)
I have two class that map two tables of my database: 我有两个类可以映射数据库的两个表:
public class Product
{
public int Id { get; set; }
public string Token { get; set; }
public string Name { get; set; }
public decimal Value { get; set; }
}
public class Ticket
{
public int Id { get; set; }
public string SerialNumber { get; set; }
public string ProductToken { get; set; }
public Product Product { get; set; }
}
For some domain reasons, Product and Ticket are logically linked, in other words, they are not linked in a database relationship that could be mapped by EF, they will be linked in my app with a linq query that "must" be translated in a SQL Outer Left Join. 由于某些领域的原因,Product和Ticket在逻辑上是链接的,换句话说,它们不是以EF可以映射的数据库关系链接的,它们将在我的应用中通过linq查询链接,该查询必须“ SQL左外部联接。 From this, i did the following query: 由此,我做了以下查询:
IQueryble<Ticket> query = from ts in context.Tickets
join ps in context.Products
on ts.ProductToken equals ps.Token into p
select new Ticket
{
Id = t.Id,
SerialNumber = t.SerialNumber,
ProductToken = t.ProductToken,
Goal -----> Product = p.FirstOrDefault()
};
The query keeps as IQueryble because after that, the query keeps to be refined with a filter. 该查询保持为IQueryble,因为此后,该查询将继续使用过滤器进行细化。
The problem is when i run the following code: 问题是当我运行以下代码时:
var tickets = query.OrderBy(t => t.SerialNumber).ToList();
I got the following error: 我收到以下错误:
"The entity or complex type 'Model.Ticket' cannot be constructed in a LINQ to Entities query."
So, how can i reach my goal? 所以,我怎么能达到我的目标?
You cannot project the result to a mapped entity, either you could project it to a annonymous type or create your own Ticket type something like: 您无法将结果投影到映射的实体,或者可以将其投影到匿名类型,或者创建自己的票证类型,例如:
public class myTicket
{
public int Id { get; set; }
public string SerialNumber { get; set; }
public string ProductToken { get; set; }
public Product Product { get; set; }
}
and then: 接着:
IQueryble<myTicket> query = from ts in context.Tickets
join ps in context.Products
on t.ProductToken equals p.Token into p
select new myTicket
{
Id = t.Id,
SerialNumber = t.SerialNumber,
ProductToken = t.ProductToken,
Product = p.FirstOrDefault()
};
Also you need to use DefaultIfEmpty() for left outer join 另外,您还需要对左外部联接使用DefaultIfEmpty()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.