首页 > 解决方案 > EF Core 3.1 到 5 更新 -> IEntityType.GetTableName

问题描述

在 EF Core 3.1 中这是有效的

// Model
builder.Entity<MyEntity>().HasNoKey().ToView("MyView", "dbo");

// Then I have this Function
public static GetTableName<T>(this MyDbContext db)
{
      var t = db.Model.FindEntityType(typeof(T));
      return t.GetTableName()
}

在 EF Core 5中t.GetTableName()返回null,因为应该使用的方法是t.GetViewName()

所以我将代码更改为

return t.GetTableName() ?? t.GetViewName()

但是我认为它“丑陋”,我宁愿检查t是视图还是表格,然后调用 right t.Get[View/Tabe]Name。但是我没有找到任何关于t它本身的属性或方法来找出它是什么。

任何想法以及如何确定它是视图还是表格?

标签: c#.netentity-framework-core

解决方案


甚至 Entity Framework Core源代码也在使用该GetViewName()方法来确定对象是否为视图

考虑到这一点,我认为您的解决方案很简洁,您可以制作自己的扩展方法,该方法完全可以隐藏“丑陋”:

public static string GetTableOrViewName(this IEntityType entityType) =>
    entityType.GetTableName() ?? entityType.GetViewName();

推荐阅读