【问题标题】:inner join in linq to entitieslinq 到实体的内部连接
【发布时间】:2011-09-04 19:03:07
【问题描述】:

我有一个名为 Customer 的实体,它具有三个属性:

public class Customer {
    public virtual Guid CompanyId;
    public virtual long Id;
    public virtual string Name;
}

我还有一个名为 Splitting 的实体,它具有三个属性:

public class Splitting {
    public virtual long CustomerId;
    public virtual long Id;
    public virtual string Name;
}

现在我需要编写一个获取 companyId 和 customerId 的方法。该方法应返回与 companyId 中的特定 customerId 相关的拆分列表。 像这样的:

public IList<Splitting> get(Guid companyId, long customrId) {    
    var res=from s in Splitting 
            from c in Customer 
            ...... how to continue?

    return res.ToList();
}

【问题讨论】:

  • 您已经粘贴了两次客户实体而不是拆分。请修复该问题
  • 为什么在get方法中需要Company ID...拆分有客户ID,可用于根据传递的客户ID进行选择
  • @Ankur:为了提高安全性,业务层公开的每个方法都需要 companyId 以验证它仅对其实体产生影响。
  • 更完整的例子请参考stackoverflow.com/a/9722744/900284

标签: c# .net linq-to-entities


【解决方案1】:
var res = from s in Splitting 
          join c in Customer on s.CustomerId equals c.Id
         where c.Id == customrId
            && c.CompanyId == companyId
        select s;

使用Extension methods

var res = Splitting.Join(Customer,
                 s => s.CustomerId,
                 c => c.Id,
                 (s, c) => new { s, c })
           .Where(sc => sc.c.Id == userId && sc.c.CompanyId == companId)
           .Select(sc => sc.s);

【讨论】:

  • 有没有办法把它写成 lambda 查询?
  • 如果您的意思是 linq 扩展方法(SelectJoin... 看看我的编辑)
  • 使用扩展方法连接多个列怎么样?
【解决方案2】:

您可以在 Visual Studio 中找到一大堆 Linq 示例。 只需选择Help -&gt; Samples,然后解压缩Linq 示例。

打开 linq 示例解决方案并打开 SampleQueries 项目的 LinqSamples.cs

您正在寻找的答案在方法 Linq14 中:

int[] numbersA = { 0, 2, 4, 5, 6, 8, 9 };
int[] numbersB = { 1, 3, 5, 7, 8 };

var pairs =
   from a in numbersA
   from b in numbersB
   where a < b
   select new {a, b};

【讨论】:

  • 我从来不知道直接在 VS 中获取样本。 +1
【解决方案3】:

不是 100% 确定这两个实体之间的关系,但这里是:

IList<Splitting> res = (from s in [data source]
                        where s.Customer.CompanyID == [companyID] &&
                              s.CustomerID == [customerID]
                        select s).ToList();

IList<Splitting> res = [data source].Splittings.Where(
                           x => x.Customer.CompanyID == [companyID] &&
                                x.CustomerID == [customerID]).ToList();

【讨论】:

    【解决方案4】:
    public IList<Splitting> get(Guid companyId, long customrId) {    
        var res=from c in Customers_data_source
                where c.CustomerId = customrId && c.CompanyID == companyId
                from s in Splittings_data_srouce
                where s.CustomerID = c.CustomerID
                select s;
    
        return res.ToList();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-08-01
      • 2010-12-03
      • 1970-01-01
      • 1970-01-01
      • 2013-10-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多