根据FK表中的记录返回列

时间:2013-03-20 22:39:07

标签: c# linq entity-framework linq-to-entities entity-framework-5

我有一个显示供应商的成功查询,但我现在要添加的是显示已选择或未选择供应商的列(显示为复选框列)。这些选择存储在VendorsSelected表中,该表包含选择它们的FK ProfileID和UserName。因此,当当前用户查看供应商时,某些供应商将会匹配,而其他供应商则不会。

如何修改查询?请注意,下面的Where子句将完成仅获取当前用户选择的供应商,但我想要的是所有供应商为他们选择的每个供应商显示的是真/假(复选框)列。

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

1 个答案:

答案 0 :(得分:2)

将属性Selectedboolean)添加到视图模型中:

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