EF Core Reflect接口属性并忽略

时间:2018-06-05 14:10:35

标签: c# entity-framework-core ef-core-2.0

我试图忽略Fluent API特定的Interface属性,例如:

public interface ITest
{
    string IgnoreThat { get; set; }
}

public class Test : ITest
{
    public string Prop1 { get; set; }
    public string PropABC { get; set; }
    public string IgnoreThat { get; set; } = "My Info";
}

public class Test2 : ITest
{
    public string PropEFG { get; set; }
    public string IgnoreThat { get; set; } = "My Info2";
}

public class Test3 : ITest
{
    public string PropExample { get; set; }
    public string IgnoreThat { get; set; } = "My Info3";
}

如果在每个课程中添加DataAnnotation [NotMapped] ,就会非常容易,如下所示:

public class Example: ITest
{
    public string PropExample { get; set; }
    [NotMapped]
    public string IgnoreThat { get; set; } = "My Info3";
}

但是我有800个类,我想在循环中执行此操作,因此,我启动此代码,但我不知道如何继续:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
        base.OnModelCreating(modelBuilder);

        var props = modelBuilder.Model.GetEntityTypes()
                .SelectMany(t => t.GetProperties())
                .Where(p=>p.Name == "IgnoreThat")
                .ToList();

        foreach (var prop in props)
        {
            //How ignore the Property?
        }
}

1 个答案:

答案 0 :(得分:2)

您可以使用ModelBuilder.Entity(Type entityType)方法获取EntityTypeBuilder实例,然后使用其Ignore(string propertyName)方法:

foreach (var prop in props)
{
    modelBuilder.Entity(prop.DeclaringEntityType.ClrType).Ignore(prop.Name);
}