我有一个成功的查询,它从连接表中返回多条记录,并生成一个 bool Selected 值(如果另一个表中的当前用户存在一条记录)。
public IEnumerable<BrowseVendorModel> SearchVendors(CustomSearchModel criteria)
{
var query = _db.VendorProfiles
.Include("VendorCategories")
.Include("VendorsSelected")
.Select(s => new BrowseVendorModel
{
ProfileID = s.ProfileID,
Name = s.Name,
CompanyName = s.CompanyName,
City = s.City,
State = s.State,
DateCreated = s.DateCreated,
// gets bool for selected vendors for current user
Selected = s.VendorsSelected.Select(vs => vs.UserName).Contains(HttpContext.Current.User.Identity.Name),
VendorsSelected = s.VendorsSelected,
VendorCategories = s.VendorCategories
})
.OrderBy(x => x.DateCreated);
return query;
}
我正在尝试编写另一个查询来检索一行,但还需要获取该 bool Selected 值而不将结果投影到上面的类中。这是我接近失败的尝试。
public VendorProfile GetVendor(String id)
{
Guid pid = Guid.Parse(id);
var viewModel = _db.VendorProfiles
.Include("VendorCategories.ProductServiceCategory")
.Include("VendorsSelected")
.Select(s => new {
VendorProfiles = s,
Selected = s.VendorsSelected.Select(vs => vs.UserName).Contains(HttpContext.Current.User.Identity.Name)
})
.Where(s => s.VendorProfiles.ProfileID == pid);
return viewModel;
}
如果为 null(没有记录匹配),我尝试生成的这个 bool 列将是 false,如果找到记录,则为 true。如果您需要模型的视觉效果,请参阅此链接