如何在 asp.net core 3.1 mvc 的另一个 table 视图中显示类别名称而不是 categoryId?

How to show category name instead of categoryId in view from another table in asp.net core 3.1 mvc?

我有两个不同的 table,其中一个是标题,另一个是类别。 标题有 4 列,分别是 Name、OWS、TWS 和 CategoryId 类别有 3 列,如 Id、Name、ParentName。

我想在标题上显示类别名称 table 而不是类别 ID。

我搜索并通过使用外键看到了一些解决方案。 CategoryId 未定义为 FK。但由于身份验证问题,我无法从数据库更改 tables。

首先,我在标题模型中声明了虚拟类别

public class Titles
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public string OWS { get; set; }
    public string TWS { get; set; }
    public Guid CategoryId { get; set; }

    public virtual Categories Category { get; set; }
}

然后我使用 TitlesController Index() 方法。当我写 CategoryId=m.CategoryId 时,我在标题 Table 上看到了 categoryId。而且我认为如果我使用 Category.Name 而不是 CategoryId,我可以在标题 Table 中看到 CategoryName。在这种情况下,我将转换类型错误作为字符串转换为系统 guid。

public async Task<IActionResult> Index()
    {

        var titles = _context.Titles
                            .Select(m => new Titles()
                            {
                                //Id=m.Id,
                                Name = m.Name,
                                OWS = m.OWS,
                                TWS = m.TWS,
                                CategoryId=m.Category.Name
                            });

       
        return View(await titles.ToListAsync());

    }

我认为,将 CategoryName 转换为 Guid 是没有意义的,而且将 CategoryId 转换为字符串可能会破坏项目的其他部分。

因此,如何在不使用 FK 的情况下显示类别名称而不是 categoryId?

您可以在您的模型中添加一个 属性 作为 NotMapped 如下所示

public class Titles
{
  public Guid Id { get; set; }
  public string Name { get; set; }
  public string OWS { get; set; }
  public string TWS { get; set; }
  public Guid CategoryId { get; set; }

  [NotMapped]
  public string CategoryName { get; set; }
  public virtual Categories Category { get; set; }
}

逻辑如下

var titles = _context.Titles.Include(t=>t.Category)
                        .Select(m => new Titles()
                        {
                            //Id=m.Id,
                            Name = m.Name,
                            OWS = m.OWS,
                            TWS = m.TWS,
                            CategoryName=m.Category.Name
                        });

你也可以制作一个单独的 Dto 而不是未映射 属性 并直接将其用作你的视图模型

您必须使用 NotMapped 属性

public class Titles
{
  public Guid Id { get; set; }
  public string Name { get; set; }
  public string OWS { get; set; }
  public string TWS { get; set; }
  public Guid CategoryId { get; set; }
  [NotMapped]
  public string CategoryName
  public virtual Categories Category { get; set; }
}

var titles = _context.Titles.Select(m => new Titles()
{
 Name = m.Name,
 OWS = m.OWS,
 TWS = m.TWS,
 CategoryName=m.Category.Name
});