table 的自定义约定,前缀为 Entity Framework

Custom Convention for table with Prefix Entity Framework

我所有的 POCO 类 都有两个字母前缀 LK_。 Entity framework 主键和外键的约定将不起作用。考虑到我有 ~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 之类的任何字段设置为 table 的主键:

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.csEF6 github。并查看使用说明测试:/ test/ EntityFramework.Core.Tests/ Metadata/ ModelConventions/ ForeignKeyPropertyDiscoveryConventionTest.cs