带有前缀实体框架的表的自定义约定
本文关键字:约定 自定义 框架 前缀 实体 | 更新日期: 2023-09-27 18:25:42
我的所有POCO类都有两个字母前缀LK_。主&外键不起作用。考虑到我有大约200个类要用Key或ForeignKey属性进行装饰,这是一个繁琐的过程&听起来并不是明智的做法。
你能建议一下风俗习惯吗?
public class LK_Employee
{
public Guid EmployeeID {get; set;}
public string Name {get; set;}
}
public class LK_Company
{
public Guid CompanyID {get; set;}
public string Name {get; set;}
}
public class LK_Employee_LK_Company
{
public Guid EmployeeID {get; set;}
public Guid CompanyID{get; set;}
}
当有一个简单的列键时,这将把任何像LK_TableName
这样的字段设置为表的主键:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Properties<Guid>()
.Where(p => "LK_" + p.Name == p.DeclaringType.Name + "Id")
.Configure(p => p.IsKey());
}
为了支持复合密钥以及简单的kesy,您需要这样做:
// Counter: keeps track of the order of the column inside the composite key
var tableKeys = new Dictionary<Type,int>();
modelBuilder.Properties<Guid>()
.Where(p =>
{
// Break the entiy name in segments
var segments = p.DeclaringType.Name.Split(new[] {"LK_","_LK_"},
StringSplitOptions.RemoveEmptyEntries);
// if the property has a name like one of the segments, it's part of the key
if (segments.Any(s => s + "ID" == p.Name))
{
// If it's not already in the column counter, adds it
if (!tableKeys.ContainsKey(p.DeclaringType))
{
tableKeys[p.DeclaringType] = 0;
}
// increases the counter
tableKeys[p.DeclaringType] = tableKeys[p.DeclaringType] + 1;
return true;
}
return false;
})
.Configure(a =>
{
a.IsKey();
// use the counter to set the order of the column in the composite key
a.HasColumnOrder(tableKeys[a.ClrPropertyInfo.DeclaringType]);
});
为外键创建约定要复杂得多。您可以在以下路径中查看EF6约定:/ src/ EntityFramework.Core/ Metadata/ Conventions/ Internal/ ForeignKeyPropertyDiscoveryConvention.cs
,在EF6-github上。有关使用说明,请参阅测试:/ test/ EntityFramework.Core.Tests/ Metadata/ ModelConventions/ ForeignKeyPropertyDiscoveryConventionTest.cs