我正在 EF 6 中尝试自定义命名约定。我有 2 个表和 1 个联结表(WebUser、UserRequest、WebUser UserRequest)。
我编写了应该能够重命名表的函数:从 WebUser 到 web_user
private string GetTableName(Type type)
{
var result = Regex.Replace(type.Name, ".[A-Z]", m => m.Value[0] + "_" + m.Value[1]);
return result.ToLower();
}
它的应用方式如下:
modelBuilder.Types()
.Configure(c => c.ToTable(GetTableName(c.ClrType)));
该函数在除连接表之外的所有表上都运行良好。
来源模型:
网络用户、用户请求
生成的数据库表:
web_user、user_request、WebUserUserRequest(而不是 web_user_user_request)
是否可以通过这种方式设置连接命名约定?有没有办法配置命名对流来处理如上所述的所有连接表(替换所有大写并添加“_”)?
可以通过这种方式添加约定来设置与 Entity Framework 6.1 中包含的公共映射 API 的关联。为此,您必须以类似的方式实现 IStoreModelConvention 接口:
public class JunctionTableConvention : IStoreModelConvention<AssociationType>
{
public void Apply(AssociationType item, DbModel model)
{
var associations = model.ConceptualToStoreMapping.AssociationSetMappings;
foreach (var association in associations)
{
var associationSetEnds = association.AssociationSet.AssociationSetEnds;
association.StoreEntitySet.Table = String.Format("{0}_{1}",
GetTableName(associationSetEnds[0].EntitySet.ElementType),
GetTableName(associationSetEnds[1].EntitySet.ElementType));
}
}
private string GetTableName(EntityType type)
{
var result = Regex.Replace(type.Name, ".[A-Z]", m => m.Value[0] + "_" + m.Value[1]);
return result.ToLower();
}
}
您必须将其包含在 DbContext 实现的 OnModelCreating 函数中,只需将其添加到 Conventions 集合中即可:
modelBuilder.Conventions.Add(new JunctionTableConvention());
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)