【问题标题】:How to use a join on three tables in Entity Framework如何在实体框架中的三个表上使用连接
【发布时间】:2018-06-30 12:35:33
【问题描述】:

我想先在实体框架代码中使用双 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# 做到这一点?

【问题讨论】:

    标签: c# sql entity-framework join


    【解决方案1】:

    这是来自docs 的示例。

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

    如果您定义了一个映射和一个 DbContext 来映射您的数据库表,那么您最好使用 .Include() 语句。 这段代码 sn-p 和官方文档应该可以启动您和您的项目。

    【讨论】:

      【解决方案2】:

      尝试使用这个:

      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();
      

      【讨论】:

        【解决方案3】:

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

        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();
        

        【讨论】:

          猜你喜欢
          • 2017-10-06
          • 1970-01-01
          • 1970-01-01
          • 2019-09-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2017-01-29
          • 1970-01-01
          相关资源
          最近更新 更多