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