[英]How to convert a SQL with multiple left joins to an Entity Framework LINQ statement using Include methods (No Join methods)?
我正在尝试将此SQL语句转换为使用Include方法(无Join Methods)的相应EF6 LINQ语句,而我无法正确获得LINQ语句。 使用LinqPad。 感谢任何帮助。
SQL:
SELECT c.CustomerName, o.Description, co.CountryName, ci.CityName
FROM Customer c
LEFT JOIN [Order] o ON c.CustId = o.CustId
LEFT JOIN Country co ON co.CountryId = o.CountryId
LEFT JOIN City ci ON ci.CityId = o.CityId
我的尝试:
сustomers.Include(c => c.Orders)
.Select(c => new { c.CustomerName, orders = c.Orders })
.AsEnumerable()
.Select(c => new { c.CustomerName, c.orders ... ? })
.Dump();
DDL:
订单表具有3个对应表的外键。
CREATE TABLE [dbo].[Customer](
[CustId] [int] NOT NULL,
[CustomerName] [varchar](50) NOT NULL,
CONSTRAINT [PK_Customer] PRIMARY KEY CLUSTERED
( [CustId] ASC )
CREATE TABLE [dbo].[Order](
[OrderId] [int] NOT NULL,
[CustId] [int] NOT NULL,
[Description] [varchar](50) NOT NULL,
[CountryId] [int] NOT NULL,
[CityId] [int] NOT NULL,
CONSTRAINT [PK_Order] PRIMARY KEY CLUSTERED
( [OrderId] ASC
CREATE TABLE [dbo].[Country](
[CountryId] [int] NOT NULL,
[CountryName] [varchar](50) NOT NULL,
CONSTRAINT [PK_Country] PRIMARY KEY CLUSTERED
( [CountryId] ASC )
CREATE TABLE [dbo].[City](
[CityId] [int] NOT NULL,
[CityName] [varchar](50) NOT NULL,
CONSTRAINT [PK_City] PRIMARY KEY CLUSTERED
( [CityId] ASC )
您基本上有2个选择:
明确地编写联接:
var q = from c in db.Customer join o in db.Order on c.CustId = o.CustId into oj // join from o in oj.DefaultIfEmpty() // left join join co in db.Country on o.CountryId equals co.CountryId into coj from co in coj join ci in db.City on o.CityId = ci.CityId into cij from ci in cij select new { c.CustomerName, o.Description, co.CountryName, ci.CityName };
或定义导航属性,然后让EF为您编写这2个联接:
var q = from c in db.Customer // .Include(c => c.Orders) ? from o in c.Orders // .DefaultIfEmpty() ? select new { c.CustomerName, o.Description, o.Country.CountryName, // those two are the (navigation) properties on the Order class o.City.CityName }; public class Order { public Customer Customer { get; set; } public City City { get; set; } // public Country Country { get; set; } } internal class OrderConfiguration : EntityTypeConfiguration<Order> { public OrderConfiguration() { // EF fluent API goes here } }
要遵循评论中的建议:
var q = from o in db.Orders
select new
{
o.Description,
o.Customer.CustomerName,
o.City.CityName,
o.City.Country.CountryName
};
也可以看看:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.