Custom Convention for table with Prefix Entity Framework

眉间皱痕 提交于 2020-01-16 02:08:08

问题


All my POCO classes have two letter prefix LK_. Entity framework conventions for primary & foreign keys would not work. Considering I have ~200 classes to decorate with Key or ForeignKey attribute its a cumbersome process & does not sound like a smart way of doing it.

Could you please suggest custom convention?

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;}        
}

回答1:


This will set any filed like LK_TableName as the table's primary key, when there is a simple column key:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Properties<Guid>()
        .Where(p => "LK_" + p.Name == p.DeclaringType.Name + "Id")
        .Configure(p => p.IsKey());
}

To support composite keys, as well as simple kesy, you need to do this:

// 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]);
});

Creating the convention for foreing keys is much more complex. You can have a look at EF6 convention in this route: / src/ EntityFramework.Core/ Metadata/ Conventions/ Internal/ ForeignKeyPropertyDiscoveryConvention.cs, on EF6 github. And see the tests for illustration of use: / test/ EntityFramework.Core.Tests/ Metadata/ ModelConventions/ ForeignKeyPropertyDiscoveryConventionTest.cs



来源:https://stackoverflow.com/questions/34088641/custom-convention-for-table-with-prefix-entity-framework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!