需要在Entity Framework中选择多个列,但只需要在单个列上进行区分

时间:2018-03-09 15:26:04

标签: c# asp.net-mvc entity-framework linq

我有一个包含以下记录的数据库表。字段比我在下面显示的字段多,但我只想返回所有者,品牌名称,ID#和类型字段。

 Owner     Ingredient        BrandName    ID#       Type

  XXX       Methoprene       Precor        123-333    H
  XXX       Permethrin       Precor        123-333    H

我正在尝试编写实体框架查询以仅选择品牌名称字段中的不同记录,但仍将列表中的其他列返回到控制器以在部分视图中显示。以下是我尝试过的代码,但我似乎无法正确编写查询:

               return db.Pesticides
                        .Where(c => c.Owner == Owner && c.BrandName == PesticidesBrand)
                        .GroupBy(c =>  c.Owner, c =>c.BrandName )
                        .Select(d => d.FirstOrDefault())
                        .ToList();

我意识到Select子句不正确,但需要帮助获取正确的语法以返回4个特定字段。我想查询返回以下记录:

XXX  Precor    123-333  H

提前致谢....

2 个答案:

答案 0 :(得分:1)

我相信这就是你要找的东西。

var record = db.Pesticides
            .Where(c => c.Owner == Owner && c.BrandName == PesticidesBrand)
            .Select(c => new { c.Owner, c.BrandName, c.ID, c.Type })
            .FirstOrDefault();

如果要从结果中返回此结果,则需要将其投影为已知类型。

PesticideModel record = db.Pesticides
            .Where(c => c.Owner == Owner && c.BrandName == PesticidesBrand)
            .Select(c => new PesticideModel{ Owner = c.Owner, BrandName = c.BrandName, ID = c.ID, Type = c.Type })
            .FirstOrDefault();

<强> PesticideModel.cs

public class PesticideModel {
    public string Owner {get;set;}
    public string BrandName {get;set;}
    public string ID {get;set;}
    public string Type {get;set;}
}

如果要返回包含单个记录的列表,请执行以下操作:

List<PesticideModel> record = db.Pesticides
            .Where(c => c.Owner == Owner && c.BrandName == PesticidesBrand)
            .Select(c => new PesticideModel{ Owner = c.Owner, BrandName = c.BrandName, ID = c.ID, Type = c.Type })
            .Take(1) // take 1st record
            .ToList();

答案 1 :(得分:0)

return db.Pesticides
.Where(c => c.Owner == Owner && c.BrandName == PesticidesBrand)
.Select(d => new Pesticide() { Owner = d.Owner, BrandName = d.BrandName, ID = d.ID, Type = d.Type })
.Distinct()
.FirstOrDefault()
.ToList();