实体框架6-代码优先:类命名空间中的表模式 [英] Entity Framework 6 - Code First: table schema from classes' namespace
本文介绍了实体框架6-代码优先:类命名空间中的表模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人知道是否可以基于类的命名空间设置代码优先类的表模式?
Does any know if one can set the table schema of code first classes based on the classes' namespace?
例如,命名空间 Core.Foo
中的每个类都具有 Foo的架构
。
For example, every class in namespace Core.Foo
would have a schema of Foo
.
推荐答案
好,您可以使用以下两个选项之一指定模式名称:
Well, you could specify the schema name using one of these two options:
-
使用数据注释:
[Table("TableName","Foo")]
public class Entity
{
}
使用 Fluent Api :
modelBuilder.Entity<Entity>().ToTable("TableName", "Foo");
在此主题上进行更多研究,我认为您正在寻找的是自定义约定 of EF:
Digging more in this subject, I think what you looking for is a Custom Convention of EF:
public class CustomSchemaConvention : Convention
{
public CustomSchemaConvention()
{
Types().Configure(c => c.ToTable(c.ClrType.Name, c.ClrType.Namespace.Substring(c.ClrType.Namespace.LastIndexOf('.') + 1)));
}
}
然后,在您的上下文中,您需要覆盖 OnModelCreating
方法添加新约定:
Then, in your context, you need to override the OnModelCreating
method to add the new convention:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Add(new CustomSchemaConvention());
}
这篇关于实体框架6-代码优先:类命名空间中的表模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文