[英]Correct way of implementing Singular Naming Convention and Data Annotations together in Entity Framework Core
I am using Entity Framework Core 2.2
and all database table names are singular so I am overriding
pluralise naming convention in OnModelCreating
method 我正在使用Entity Framework Core 2.2
并且所有数据库表名称都是单数,因此我在OnModelCreating
方法中overriding
复数命名约定
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
foreach (IMutableEntityType entityType in modelBuilder.Model.GetEntityTypes())
{
entityType.Relational().TableName = entityType.DisplayName();
}
}
However in some cases entity names are different to table names for example 但是,在某些情况下,例如实体名称与表名称不同
[Table("AzureSchemaVersionExecutionExtract", Schema = "dbo")]
public class AzureDataExtract
{
public int Id { get; set; }
public DateTime DateApplied { get; set; }
}
When i run the project it complains as it cannot find the table AzureDataExtract
so i added following code in OnModelCreating
method and it works. 当我运行该项目时,它抱怨说找不到表AzureDataExtract
因此我在OnModelCreating
方法中添加了以下代码,并且可以正常工作。 I need to know is this the correct way to implement Data Annotations
and Singular Naming Convention
together 我需要知道这是一起实现Data Annotations
和Singular Naming Convention
的正确方法
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
foreach (IMutableEntityType entityType in modelBuilder.Model.GetEntityTypes())
{
entityType.Relational().TableName = entityType.DisplayName();
}
modelBuilder.Entity<AzureDataExtract>().ToTable("AzureSchemaVersionExecutionExtract","dbo");
}
It's possible, but not with public API. 可以,但是不能使用公共API。 But you already are using methods from Microsoft.EntityFrameworkCore.Metadata.Internal
namespace, so that shouldn't be a problem - just check out if something is changed when upgrading to a newer EF Core version and update accordingly. 但是您已经在使用Microsoft.EntityFrameworkCore.Metadata.Internal
命名空间中的方法,所以这应该不成问题-只需检查升级到较新的EF Core版本并进行相应更新时是否有所更改。
In EF Core 2.2 the trick is to use the internal Relational()
method accepting ConfigurationSource
and pass ConfigurationSource.Convention
. 在EF Core 2.2中,技巧是使用内部的Relational()
方法接受ConfigurationSource
并传递ConfigurationSource.Convention
。 Data annotations and regular fluent API have higher priority, so this will only override the internal EF Core table name convention which uses the DbSet
name. 数据批注和常规fluent API具有更高的优先级,因此这只会覆盖使用DbSet
名称的内部EF Core表名称约定。
foreach (var entityType in modelBuilder.Model.GetEntityTypes().Where(t => !t.IsOwned())
{
entityType.AsEntityType().Builder.Relational(ConfigurationSource.Convention)
.ToTable(entityType.DisplayName());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.