EF Core 反映接口属性并忽略
EF Core Reflect interface properties and ignore
我试图通过 Fluent API 特定界面 属性 忽略,示例:
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";
}
如果在每个 class 中添加 DataAnnotation [NotMapped],就很容易了,就像这样:
public class Example: ITest
{
public string PropExample { get; set; }
[NotMapped]
public string IgnoreThat { get; set; } = "My Info3";
}
但是我有 800 个 classes,我想循环执行此操作,所以,我开始这段代码,但我不知道如何继续:
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?
}
}
您可以使用 ModelBuilder.Entity(Type entityType)
方法获取 EntityTypeBuilder
实例,然后使用它的 Ignore(string propertyName)
方法:
foreach (var prop in props)
{
modelBuilder.Entity(prop.DeclaringEntityType.ClrType).Ignore(prop.Name);
}
我试图通过 Fluent API 特定界面 属性 忽略,示例:
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";
}
如果在每个 class 中添加 DataAnnotation [NotMapped],就很容易了,就像这样:
public class Example: ITest
{
public string PropExample { get; set; }
[NotMapped]
public string IgnoreThat { get; set; } = "My Info3";
}
但是我有 800 个 classes,我想循环执行此操作,所以,我开始这段代码,但我不知道如何继续:
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?
}
}
您可以使用 ModelBuilder.Entity(Type entityType)
方法获取 EntityTypeBuilder
实例,然后使用它的 Ignore(string propertyName)
方法:
foreach (var prop in props)
{
modelBuilder.Entity(prop.DeclaringEntityType.ClrType).Ignore(prop.Name);
}