简体   繁体   中英

EF Core Reflect interface properties and ignore

I'm trying to ignore by Fluent API specific Interface property, example:

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";
}

It's very easy if in each class i add DataAnnotation [NotMapped] , like this:

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

But i have 800 classes, and i want to do this in loop, so, i start this code, but i don't know how continue:

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?
        }
}

You could use ModelBuilder.Entity(Type entityType) method to get the EntityTypeBuilder instance and then use its Ignore(string propertyName) method:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM