Selecting one bool column from another table

 ̄綄美尐妖づ 提交于 2019-12-11 13:17:06

问题


I have a successful query that returns multiple records from a joined table and also generates a bool Selected value (if a record exists for the current user in another table).

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;
}

I am trying to write another query that retreives one row but also needs to obtain that bool Selected value without projecting results into a class like the one above. This is my failed attempt to come close.

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;
}

This bool column I am trying to generate would be false if null (no records match) and true if a record is found. see this link if you need a visual of the model


回答1:


In this case since I only wanted one extra bool value to display on the page and as this was an Edit page in which the view model would have to be mapped back to the domain model... Seemed like too much work for a single bool column, so I went with a separate query that populates a ViewBag :)



来源:https://stackoverflow.com/questions/15671371/selecting-one-bool-column-from-another-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!