【问题标题】:Selecting one bool column from another table从另一个表中选择一个布尔列
【发布时间】:2023-04-05 02:51:01
【问题描述】:

我有一个成功的查询,它从一个连接的表中返回多条记录,并生成一个 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;
}

如果为 null(没有记录匹配),我尝试生成的这个 bool 列将为 false,如果找到记录,则为 true。如果您需要模型的视觉效果,请参阅此link

【问题讨论】:

  • 那么在第二个查询中什么不起作用?
  • @abatishchev 这不是编写查询的正确方法,我不知道如何处理它。也许我必须将其投影到自定义视图模型中才能使其正常工作,但希望不要这样做。
  • 很明显viewModel 是匿名类型,而VendorProfile 是预期的。看来您必须引入另一个视图模型。
  • @GertArnold 是的,我明白你的意思。如果不创建自定义视图模型,我无法将新字段引入现有域模型

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


【解决方案1】:

在这种情况下,因为我只希望在页面上显示一个额外的 bool 值,并且这是一个编辑页面,其中视图模型必须映射回域模型......看起来工作量太大了一个布尔列,所以我使用了一个单独的查询来填充 ViewBag :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-30
    • 1970-01-01
    • 2021-12-30
    • 2019-03-09
    • 1970-01-01
    • 2016-07-22
    • 1970-01-01
    • 2013-07-17
    相关资源
    最近更新 更多