C# 使用接口的抽象属性行为
我有一个ITiming接口:C# 使用接口的抽象属性行为,c#,entity-framework,entity-framework-core,ef-core-2.1,C#,Entity Framework,Entity Framework Core,Ef Core 2.1,我有一个ITiming接口: public interface ITiming { DateTime CreatedAt { get; set; } DateTime UpdatedAt { get; set; } } 还有几个实现它的类: public class Post : ITiming { public int IdPost { get; set; } public string Title { get; set; } public DateT
public interface ITiming
{
DateTime CreatedAt { get; set; }
DateTime UpdatedAt { get; set; }
}
还有几个实现它的类:
public class Post : ITiming
{
public int IdPost { get; set; }
public string Title { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
}
在我的模型生成器中,我正在为每个实现它的实体设置AfterSaveBehavior
,如下所示:
modelBuilder.Entity<Post>(entity =>
{
entity.HasKey(e => e.IdPost);
entity.Property(e => e.CreatedAt)
.Metadata.AfterSaveBehavior = PropertySaveBehavior.Ignore;
});
你就快到了。只需使用即可访问属性可变元数据:
foreach (var entityType in modelBuilder.Model.GetEntityTypes())
{
if (typeof(ITiming).IsAssignableFrom(entityType.ClrType))
{
entityType.FindProperty(nameof(ITiming.CreatedAt))
.AfterSaveBehavior = PropertySaveBehavior.Ignore;
}
}
或者,您可以忽略该接口并应用自定义的DateTime CreatedAt
属性约定:
foreach (var property in modelBuilder.Model.GetEntityTypes()
.SelectMany(t => t.GetProperties())
.Where(p => p.ClrType == typeof(DateTime) && p.Name == "CreatedAt"))
{
property.AfterSaveBehavior = PropertySaveBehavior.Ignore;
}
foreach (var property in modelBuilder.Model.GetEntityTypes()
.SelectMany(t => t.GetProperties())
.Where(p => p.ClrType == typeof(DateTime) && p.Name == "CreatedAt"))
{
property.AfterSaveBehavior = PropertySaveBehavior.Ignore;
}