如何在Entity Framework中的三个表上使用连接

时间:2018-01-21 21:54:46

标签: c# sql entity-framework join

我想在代码优先的代码框架中使用双SQL连接。我可以使用SQL查询来完成它,但我无法将其转换为C#实体代码。

我的SQL代码是:

SELECT 
    CS.CustomerId, CS.CustomerName, SF.FactorId, SD.SaleDate
FROM 
    [dbo].[SaleFactors] SF
JOIN
    [dbo].[Customers] CS ON SF.CustomerId = CS.CustomerId
JOIN
    (SELECT DISTINCT
         [FactorId], [SaleDate]
     FROM 
         [dbo].[SaleProducts]
     WHERE
         SaleDate >= 2016 AND SaleDate <= 2018) SD ON SD.FactorId = SF.FactorId

我怎样才能使用C#?

3 个答案:

答案 0 :(得分:0)

以下是docs

中的示例
using (var context = new BloggingContext())
{
    var blogs = context.Blogs
        .Include(blog => blog.Posts)
        .Include(blog => blog.Owner)
        .ToList();
}

如果您有映射和DbContext定义来映射数据库表,那么您最好使用.Include()语句。 此代码段和官方文档应该启动您和您的项目。

答案 1 :(得分:0)

尝试使用它:

using (var context = new YourContext())
{
    var result = context.SaleFactors
            .Where(x => x.SaleProducts.SaleDate >= 2016  &&x.SaleProducts.SaleDate <= 2018 )
            .Select(x => new
  {
     FactorId = x.FactorId ,
     CustomerId = x.Customers.CustomerId  ,
     CustomerName = x.Customers.CustomerName ,
     SaleDate = x.SaleProducts.SaleDate .

  }).Distinct().ToList();

答案 2 :(得分:0)

非常感谢。 我解决了它,它是我的代码:

var varGetSaleInformation = (from factor in oDatabaseContext.SaleFactors
    join sale in oDatabaseContext.SaleProducts
      on factor.FactorId equals sale.FactorId
        where sale.SaleDate >= 2016 && sale.SaleDate <= 2018
    join customer in oDatabaseContext.Customers
      on factor.CustomerId equals customer.CustomerId
        where factor.CustomerId.ToString().Contains(txtFactorId.Text)
    select new
    {
        customerId = customer.CustomerId,
        customerName = customer.CustomerName,
        factorId = factor.FactorId,
        factorPaymentType = factor.FactorPaymentType,
        saleDate = sale.SaleDate
    }).Distinct().ToList();