c# - 忽略 EF CodeFirst 中所有已实现的接口(interface)属性

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

不久前,我对 edmx 模型使用了数据库优先方法。我创建了部分类来扩展 edmx 生成的域模型的功能。

//Generated by tt in edmx
public partial class DomainObject
{
    public int PropertyA {get; set;}
    public int PropertyB {get; set;}
}

//My own partial that extends functionality on generated one       
public partial class DomainObject: IDomainEntity
{
    public int EntityId {get; set;}
    public int EntityTypeId {get; set;}
    public int DoSomethingWithCurrentEntity()
    {
        //do some cool stuff
        return 0;
    }
}

所有部分都实现了接口(interface)IDomainEntity

public interface IDomainEntity
{
    int EntityId {get; set;}
    int EntityTypeId {get; set;}
    int DoSomethingWithCurrentEntity();

    //Another huge amount of properties and functions
}

所以这个接口(interface)的所有属性都没有映射到数据库中的表

现在我已经迁移到 Code First 方法,所有这些属性都试图映射到数据库。当然我可以使用 [NotMapped] 属性,但接口(interface)和类中的属性数量巨大(超过 300 个)并且还在继续增长。是否有任何方法可以一次忽略所有类的部分或接口(interface)的所有属性。

最佳答案

您可以使用反射找出要忽略的属性,然后在 DbContext.OnModelCreating 方法中使用 Fluent API 忽略它们:

foreach(var property in typeof(IDomainEntity).GetProperties())
    modelBuilder.Types().Configure(m => m.Ignore(property.Name));

关于c# - 忽略 EF CodeFirst 中所有已实现的接口(interface)属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31175785/

相关文章:

c# - MVVM 将 View 绑定(bind)到可变模型

mysql - 引用的列必须是目标实体原则上的主键列 - Symfony2

c# - Entity Framework ID 自动递增

ef-code-first - 如何暂时关闭 EF Code First 中的 IDENTITY 列?

sql - EF Core 检查约束

c# - 计算对数算法的时间

c# - 从 C# 中的 HTTPWebResponse.GetResponseStream() 上传到 S3

c# - 如何在表单加载时删除所有 DataGridView 行?

c# - ASP.NET MVC 4 EF6 无法连接到 SQL Server Express 数据库

c# - 在代码优先 Entity Framework 中定义多对多关系