【问题标题】:Ignoring all implemented interface properties in EF CodeFirst忽略 EF CodeFirst 中所有实现的接口属性
【发布时间】:2015-07-02 04:48:55
【问题描述】:

不久前,我在 edmx 模型中使用了 DataBase First 方法。我创建了部分类来扩展 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;
    }
}

所有部分都在实现接口 IDomainEntity

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

    //Another huge amount of properties and functions
}

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

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

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

    • 会影响性能吗?除了少数之外,有没有什么方法可以忽略所有技巧?
    • @Anton 你不能在这里简单地忽略类型,因为实体有自己的属性。至于性能,据我所知,实体模型每个应用程序域构建一次,因此它可以最大程度地提高启动性能。
    • EF5 有什么用吗?我正在维护一个使用 EF5 的遗留项目。 Types 未在 EF5 中公开。
    猜你喜欢
    • 2017-06-03
    • 2013-09-14
    • 1970-01-01
    • 2018-12-11
    • 1970-01-01
    • 2018-03-03
    • 1970-01-01
    • 2018-10-22
    • 1970-01-01
    相关资源
    最近更新 更多