使用的是 Entity Framework Core 2.0 (2.0.0-preview2-final)。正式版发布时,功能可能存在变动。
Entity Framework 迁移允许从模型生成数据库,这意味着必须从类名和属性名生成数据库对象的名称。对于大多数人来说使用默认名称是没有问题的,但是,您的DBA可能会要求您使用特定的命名约定。例如,一些DBA希望表名大写,或者列名使用表名为前缀。
Entity Framework 允许逐个设置表名或列名:
protected override void OnModelCreating(ModelBuilder modelBuilder){ modelBuilder.Entity<Blog>().ForSqlServerToTable("Blog"); }
但是,写这些代码非常无聊并且容易出错,不应该逐个设置对像的名称,您可以通过修改模型实现全局设置。事实上modelBuilder
是可读写的,您可以迭代所有对象并更改其名称。
public class BloggingContext : DbContext{ public DbSet<Blog> Blogs { get; set; } public DbSet<Post> Posts { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); // Singularize table name // Blogs => Blog foreach (var entityType in modelBuilder.Model.GetEntityTypes()) { // Add NuGet package "Humanizer" to use Singularize() entityType.Relational().TableName = entityType.Relational().TableName.Singularize(); } // Prefix column names with table name // Id => Blog_Id foreach (var entityType in modelBuilder.Model.GetEntityTypes()) { foreach (var property in entityType.GetProperties()) { property.Relational().ColumnName = entityType.Relational().TableName + "_" + property.Relational().ColumnName; } } // Rename Foreign Key // FK_Post_Blog_BlogId => FK_Post_Blog_BlogId_Test foreach (var entityType in modelBuilder.Model.GetEntityTypes()) { foreach (var property in entityType.GetProperties()) { foreach (var fk in entityType.FindForeignKeys(property)) { fk.Relational().Name = fk.Relational().Name + "_Test"; } } } // Rename Indices // IX_Blog_Url => IX_Blog_Url_Test foreach (var entityType in modelBuilder.Model.GetEntityTypes()) { foreach (var index in entityType.GetIndexes()) { index.Relational().Name = index.Relational().Name + "_Test"; } } } }
在 Package Manager Console 中运行以下命令:
Add-Migration NamingConvention Update-Database
上面的命令将生成以下数据库架构:
CREATE TABLE [dbo].[Blog] ( [Blog_BlogId] INT IDENTITY (1, 1) NOT NULL, [Blog_Url] NVARCHAR (450) NULL, CONSTRAINT [PK_Blog] PRIMARY KEY CLUSTERED ([Blog_BlogId] ASC) );CREATE UNIQUE NONCLUSTERED INDEX [IX_Blog_Url_Test] ON [dbo].[Blog]([Blog_Url] ASC) WHERE ([Blog_Url] IS NOT NULL);CREATE TABLE [dbo].[Post] ( [Post_PostId] INT IDENTITY (1, 1) NOT NULL, [Post_BlogId] INT NOT NULL, [Post_Content] NVARCHAR (MAX) NULL, [Post_Title] NVARCHAR (MAX) NULL, CONSTRAINT [PK_Post] PRIMARY KEY CLUSTERED ([Post_PostId] ASC), CONSTRAINT [testFK_Post_Blog_BlogId] FOREIGN KEY ([Post_BlogId]) REFERENCES [dbo].[Blog] ([Blog_BlogId]) ON DELETE CASCADE);CREATE NONCLUSTERED INDEX [IX_Post_BlogId_Test] ON [dbo].[Post]([Post_BlogId] ASC);
您可以看到生成数据库对象名称遵循的命名约定。
本文转自 zddnd 51CTO博客,原文链接:http://blog.51cto.com/13013666/1949227