EF Core Reflect接口属性并忽略

问题描述 投票:1回答:1

我试图忽略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?
        }
}
c# entity-framework-core ef-core-2.0
1个回答
2
投票

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

foreach (var prop in props)
{
    modelBuilder.Entity(prop.DeclaringEntityType.ClrType).Ignore(prop.Name);
}
© www.soinside.com 2019 - 2024. All rights reserved.