使用C#MVC5 Visual studio 2015。
我有一个包含以下代码的方法:
public List<OffersOnPropertyViewModel> Build(string buyerId)
{
var filtered = _context.Properties.Where(x => x.Offers.Any(c => c.BuyerUserId == buyerId)).ToList();
var model = filtered.Select(c =>
{
var item = new OffersOnPropertyViewModel()
{
PropertyType = c.PropertyType,
NumberOfBedrooms = c.NumberOfBedrooms,
StreetName = c.StreetName,
Offers = c.Offers.Where(d => d.BuyerUserId == buyerId).Select(x => new OfferViewModel
{
Id = x.Id,
Amount = x.Amount,
CreatedAt = x.CreatedAt,
IsPending = x.Status == OfferStatus.Pending,
Status = x.Status.ToString(),
BuyerUserId = x.BuyerUserId
}),
};
return item;
}).ToList();
//TODO: refactor, shorten linq, duping where clause
return model;
}
以下是模型:
public class Property
{
[Key]
public int Id { get; set; }
[Required]
public string PropertyType { get; set; }
[Required]
public string StreetName { get; set; }
[Required]
public string Description { get; set; }
[Required]
public int NumberOfBedrooms { get; set; }
[Required]
public string SellerUserId { get; set; }
public bool IsListedForSale { get; set; }
public ICollection<Offer> Offers { get; set; }
}
在DB Offers表中,属性id为其FK。
该方法在运行时失败,说Value不能为null。
当我单步执行时,我注意到过滤后的结果(在示例中为1个结果),表示商品为空。虽然查询只根据&#34; x.Offers&#34;。
过滤了结果我只需要一种方法来检索由buyerId提供的商品列表。我的方法有误吗?或者我错过了一个班轮?
由于
答案 0 :(得分:3)
您需要在LINQ查询中添加Include()
以引入子对象,如下所示:
var filtered = _context.Properties.Include("Offers")
.Where(x => x.Offers.Any(c => c.BuyerUserId == buyerId)).ToList();
您的过滤器与Any()
一起使用的原因是,在生成SQL查询时,此部分形成WHERE
子句,但未包含在SELECT
中。