gpt4 book ai didi

c# - Entity Framework Core 约定在哪里?

转载 作者:可可西里 更新时间:2023-11-01 08:05:45 31 4
gpt4 key购买 nike

使用 EF 6.1+ 时,我们有时需要添加或删除现有限制。代码看起来或多或少像:

public class MyContext : DbContext
{
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.AddFromAssembly(Assembly.GetExecutingAssembly());
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();

base.OnModelCreating(modelBuilder);
}
}

如何在 EF 核心中做同样的事情? Modelbuilder 没有 Conventions 属性 :(

最佳答案

我正在将一些代码从 EF 移植到 EF Core 2.1+,等不及 EF Core 3.0,所以写了一些扩展方法,这有点帮助..

public static IEnumerable<IMutableEntityType> EntityTypes(this ModelBuilder builder)
{
return builder.Model.GetEntityTypes();
}

public static IEnumerable<IMutableProperty> Properties(this ModelBuilder builder)
{
return builder.EntityTypes().SelectMany(entityType => entityType.GetProperties());
}

public static IEnumerable<IMutableProperty> Properties<T>(this ModelBuilder builder)
{
return builder.EntityTypes().SelectMany(entityType => entityType.GetProperties().Where(x => x.ClrType == typeof(T)));
}

public static void Configure(this IEnumerable<IMutableEntityType> entityTypes, Action<IMutableEntityType> convention)
{
foreach (var entityType in entityTypes)
{
convention(entityType);
}
}

public static void Configure(this IEnumerable<IMutableProperty> propertyTypes, Action<IMutableProperty> convention)
{
foreach (var propertyType in propertyTypes)
{
convention(propertyType);
}
}

例如,您可以使用这些编写类似于 EF 6.1.x 中的约定。

// equivalent of modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.EntityTypes()
.Configure(et => et.Relational().TableName = et.DisplayName());

// Put the table name on the primary key
modelBuilder.Properties()
.Where(x => x.Name == "Id")
.Configure(p => p.Relational().ColumnName = p.DeclaringEntityType.Name + "Id");

// Mark timestamp columns as concurrency tokens
modelBuilder.Properties()
.Where(x => x.Name == "Timestamp")
.Configure(p => p.IsConcurrencyToken = true);

对于 EF Core 3.0,元模型方法略有变化,因此您需要

modelBuilder.EntityTypes()
.Configure(et => et.SetTableName(et.DisplayName()));

modelBuilder.Properties()
.Where(x => x.Name == "Id")
.Configure(p => p.SetColumnName(BaseName(p.DeclaringEntityType.Name) + "Id"));

还没有检查这个效率但是除非你的模型很大它不应该造成问题

这可以通过外键、索引等其他助手进行扩展

关于c# - Entity Framework Core 约定在哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46837617/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com