无法获得适当的实体价值

时间:2013-10-10 18:38:30

标签: c# linq asp.net-mvc-4 entity-framework-4 ef-code-first

我尝试了很多,但我无法通过互联网找到任何解决方案。我试图获取集合中属性的值。

这是DeliveryShop实体:

[Key]
public int DeliveryShopId { get; set; }
public int MinOrderForDelivery { get; set; }
public bool HasDelivery { get; set; }
public bool HasTakeAway { get; set; }

public virtual List<Location> Locations { get; set; }

这是位置实体:

[Key]
public int LocationId { get; set; }
public int DeliveryShopId { get; set; }
public string City { get; set; }
public string Country { get; set; }
public string ZIP { get; set; }
public virtual DeliveryShop DeliveryShop { get; set; }

这是我对索引操作方法的查询:

viewModel.DeliveryShop = db.DeliveryShops.Where(c => c.Locations.Where(l => l.City == "Berlin")).ToList();

我收到错误,我想展示只在柏林的商店。

1 个答案:

答案 0 :(得分:0)

你的LINQ没有意义。应该是:

viewModel.DeliveryShop = db.DeliveryShops
  .Where(c => c.Locations
    .Any(l => l.City == "Berlin"))
  .ToList();

LINQ Where Method需要Func<TSource, bool> predicate(返回bool的方法)。以下代码不返回bool:

c.Locations.Where(l => l.City == "Berlin")

在评论中提及Pawel的另一种方法是:

viewModel.DelipveryShop = db.Locations
  .Where(l => l.City == "Berlin") // returns IQueryable<Location>
  .Select(l => l.DeliveryShop)    // returns IQueryable<DeliveryShop>
  .ToList();  // returns List<DeliveryShop>