【问题标题】:3 tables linq join plus foreach3 个表 linq join 加 foreach
【发布时间】:2017-03-02 21:56:44
【问题描述】:

三个表:

地理数据: 身份证

地址: ID、GeoDataID、用户ID

产品: ID、用户ID

GeoData.ID 和 Address.GeoDataID 之间存在一对一关系,Address.UserID 和 Products.UserID 之间存在一对多关系

我有一个 GeoData ID 数组作为输入,我想获取所有相关产品。

如果我只有一个 GeoData ID,我会尝试类似:

int geoDataID = 3456;
        using (var context = new BaseContext())
        {
            from p in context.Products
            join a in context.Addresses on p.UserID equals a.UserID
            join g in context.GeoData on a.GeoDataID equals g.ID
            where g.ID == geoDataID
            select new { p };
        }

但由于我有一个数组 (int[] geoData) 作为输入,我无法将它放在一起。

【问题讨论】:

  • 如果geoDataIDint[],那么where geoDataID.contains(g.ID)
  • 对不起,我不明白您的评论:这应该是获得预期结果的解决方法吗?
  • 不清楚你在问什么,但如果geoDataIDint[] geoDataID = new int[]{ 1, 2, 3 } 然后用我第一条评论中的代码替换where g.ID == geoDataID
  • 虽然我不明白为什么你需要加入GeoData,而你可以使用AddressGeoDataID

标签: asp.net-mvc linq foreach


【解决方案1】:

试试这个:

using (var context = new BaseContext())
        {
         var results =   from p in context.Products
            join a in context.Addresses on p.UserID equals a.UserID
            where geoData.Contains(a.geoDataID)
            select p;
        }

【讨论】:

  • 谢谢,这符合预期。还有“geoDataID.Any(item => item == a.GeoDataID)”。是否有任何理由更喜欢“包含”而不是“任何”方法?
【解决方案2】:

您需要做的就是对地理数据 ID 的集合使用 Contains() 方法来过滤您想要的记录。

public IEnumerable<Product> GetProductsByGeoData(IEnumerable<int> geoDataIds)
{
    var products = context.GeoData
        .Where(gd => geoDataIds.Contains(gd.Id))
        .Join(context.Addresses,
            gd => gd.Id,
            a => a.GeoDataId,
            (gd, a) => a)
        .Join(context.Products,
            a => a.UserId,
            p => p.UserId,
            (a, p) => p);
    return products;

}

【讨论】:

  • 我有一个 int 数组作为输入。您的建议需要一个 Ienumerable(或者可能是 Ienumerable)。我不知道如何将我的实际输入转换为所需的 ienumerable。
  • @Luke,一个 int 数组 (int[]) IEnumerable&lt;int&gt;
猜你喜欢
  • 2016-10-14
  • 1970-01-01
  • 2017-12-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-19
  • 1970-01-01
  • 2023-03-31
相关资源
最近更新 更多