Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
262 views
in Technique[技术] by (71.8m points)

c# - Return column based on record in FK table

I have a success query for displaying Vendors, but what I wanted to add now is a column showing which vendors have been selected or not (displayed as a checkbox column). These selections are stored in VendorsSelected table that contains the FK ProfileID and UserName that selected them. So when the current user views the Vendors there will be matches for some Vendors and not for others.

How do I modify the query? Note the Where clause below will accomplish getting only vendors that the current user has selected, but what I want is all vendors displayed with true/false (checkbox) column for each vendor they have selected.

public IEnumerable<BrowseVendorModel> BrowseVendors()
{
    IQueryable<BrowseVendorModel> viewModel = _db.VendorProfiles
        .Include("VendorsSelected")
        .Select(s => new BrowseVendorModel
        {
            ProfileID = s.ProfileID,
            Name = s.Name,
            CompanyName = s.CompanyName,
            City = s.City,
            State = s.State,
            DateCreated = s.DateCreated
        })
        .Where(x => x.VendorsSelected.Select(s => s.UserName).Contains(HttpContext.Current.User.Identity.Name))
        .OrderBy(v => v.ProfileID);

    return viewModel;
}

enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Add a property Selected (boolean) to the view model:

public IEnumerable<BrowseVendorModel> BrowseVendors()
{
    IQueryable<BrowseVendorModel> viewModel = _db.VendorProfiles
        .Include("VendorsSelected")
        .Select(s => new BrowseVendorModel
        {
            ProfileID = s.ProfileID,
            Name = s.Name,
            CompanyName = s.CompanyName,
            City = s.City,
            State = s.State,
            DateCreated = s.DateCreated,
            Selected = x.VendorsSelected.Select(s => s.UserName)
                        .Contains(HttpContext.Current.User.Identity.Name)
        })
        .OrderBy(v => v.ProfileID);

    return viewModel;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...