我有一个成功的查询,它从连接表中返回多个记录,并且还生成一个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;
}
我试图生成的bool列如果为null(没有记录匹配)则为false,如果找到记录则为true。如果您需要模型的视觉效果,请参阅此link
答案 0 :(得分:0)
在这种情况下,因为我只想在页面上显示一个额外的bool值,因为这是一个Edit页面,其中视图模型必须映射回域模型...看起来像是太多的工作一个bool列,所以我选择了一个填充ViewBag的单独查询:)