c# - Entity Framework 数据库首先从基类继承模型

标签 c# entity-framework ef-database-first database-first

我使用 Entity Framework Database First 来处理数据库。

我有一个基类EntityBase

public class EntityBase
{        
    public Int32 Id { get; set; }
}

我还有一些由 EnitytFramework 生成的其他类,代表我的数据库的表,例如“User”类:

public class User
{
  public int32 Id{get;set;} 
  public class Name{get;set;}
  public class Age{get;set;}
}

我希望所有 EF 模型类都从 EntityBase 继承:

public class User : EntityBase

我可以通过从 User 类中删除 Id 字段并定义继承来手动执行此操作,但是在我从数据库更新模型后,所有手动更改都会消失。 有什么方法可以保留或自动添加对 EF 模型类的继承吗?

最佳答案

如果您手动更改类、保存并编译,EF 数据库首先使用 t4 文件,T4 将再次生成类,并且您会丢失更改。 您必须在 T4 模板中进行此更改。搜索EntityClassOpening方法并更改最后一行:

_typeMapper.GetTypeName(entity.BaseType)

使用此代码:

_typeMapper.GetTypeName(entity.BaseType) ?? "EntityBaseClass"

关于c# - Entity Framework 数据库首先从基类继承模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17171440/

相关文章:

c# - 代码优先,当我启用迁移时,我得到 “No context type was found in the assembly ' DOC'”

asp.net-mvc - MVC + EF DB-First 单元测试

sql-server - 使用具有复合键和更新级联功能的 SQL Server 数据库进行 ASP.NET MVC 编码

c# - 在 JSON.NET 中序列化 null

c# - 重载方法是否可以转换其参数然后调用其原始方法?

c# - EF如何附加实体

c# - Entity Framework 抛出无法在表中插入标识列的显式值

entity-framework-4.1 - Entity Framework 4.1 Database First 未向 DbContext T4 生成的类添加主键

c# - 使用两个 Redis 实例 - 类似于 Mongos

c# - EF 6 代码首先将 IEnumerable<> 转换为 Json "Self referencing loop detected with type..."