我終於找到了一個答案,通過編寫一個自定義約定。該慣例適用於EF 6.0 RC1(上週的代碼),所以我認爲在EF 6.0發佈後它可能會繼續工作。
使用此方法,標準EF約定標識獨立關聯(IAs),然後爲外鍵字段創建EdmProperty。然後這個約定出現並重命名外鍵字段。
/// <summary>
/// Provides a convention for fixing the independent association (IA) foreign key column names.
/// </summary>
public class ForeignKeyNamingConvention : IStoreModelConvention<AssociationType>
{
public void Apply(AssociationType association, DbModel model)
{
// Identify a ForeignKey properties (including IAs)
if (association.IsForeignKey)
{
// rename FK columns
var constraint = association.Constraint;
if (DoPropertiesHaveDefaultNames(constraint.FromProperties, constraint.ToRole.Name, constraint.ToProperties))
{
NormalizeForeignKeyProperties(constraint.FromProperties);
}
if (DoPropertiesHaveDefaultNames(constraint.ToProperties, constraint.FromRole.Name, constraint.FromProperties))
{
NormalizeForeignKeyProperties(constraint.ToProperties);
}
}
}
private bool DoPropertiesHaveDefaultNames(ReadOnlyMetadataCollection<EdmProperty> properties, string roleName, ReadOnlyMetadataCollection<EdmProperty> otherEndProperties)
{
if (properties.Count != otherEndProperties.Count)
{
return false;
}
for (int i = 0; i < properties.Count; ++i)
{
if (!properties[i].Name.EndsWith("_" + otherEndProperties[i].Name))
{
return false;
}
}
return true;
}
private void NormalizeForeignKeyProperties(ReadOnlyMetadataCollection<EdmProperty> properties)
{
for (int i = 0; i < properties.Count; ++i)
{
string defaultPropertyName = properties[i].Name;
int ichUnderscore = defaultPropertyName.IndexOf('_');
if (ichUnderscore <= 0)
{
continue;
}
string navigationPropertyName = defaultPropertyName.Substring(0, ichUnderscore);
string targetKey = defaultPropertyName.Substring(ichUnderscore + 1);
string newPropertyName;
if (targetKey.StartsWith(navigationPropertyName))
{
newPropertyName = targetKey;
}
else
{
newPropertyName = navigationPropertyName + targetKey;
}
properties[i].Name = newPropertyName;
}
}
}
注意該公約被添加到您的DbContext
在DbContext.OnModelCreating
覆蓋,使用:
modelBuilder.Conventions.Add(new ForeignKeyNamingConvention());
你不能這樣做 - 但。有一個[可定製的代碼優先開發功能的約定](http://msdn.microsoft.com/en-us/data/jj819164.aspx)正在爲EF 6.0工作,但現在 - 你必須處理這個你自己,手動... –
我實際上使用EF6 alpha 2.是否有可能以這種方式使用它? –
[查看此博客文章](http://blog.3d-logic.com/2013/03/24/my-first-encounter-with-custom-conventions-in-entity-framework-6/) - this同事似乎在做一些類似於你想要的事情。 –