Selecting one bool column from another table

2019-08-03 17:30发布

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条回答
Rolldiameter
2楼-- · 2019-08-03 18:26

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 :)

查看更多
登录 后发表回答