Entity Framework 6 Custom Relationship Convention(实体框架 6 自定义关系约定)
问题描述
我已阅读 this 有关实体框架 6 中约定的文档.但它不包含关系的约定.
I have read this documentation about convention in Entity Framework 6. But it does not contain convention for Relationship.
假设我有以下模型:
[TablePrefix("mst")]
public class Guru
{
public int Id { get; set; }
public int? IdKotaLahir { get; set; }
public virtual Kota KotaLahir { get; set; }
}
我希望属性 IdKotaLahir
成为导航属性 KotaLahir
的外键.外键名称为 "Id"+
.是否可以使用当前版本的实体框架(EF 6 alpha 3)?
I want property IdKotaLahir
to be foreign key of navigation property KotaLahir
.
Foreign key name is "Id"+<NavigationPropertyName>
.
Is it possible using current version of entity framework (EF 6 alpha 3)?
推荐答案
它只是一个属性还是你需要它(即整个模型使用外键名称始终为Id"+ NavigationPropertyName 的约定)?如果您只想要单个实体的外键,最好使用 ForeignKey
属性:
Is it just one property or you need this across the board (i.e. the whole model is using a convention where foreign key names are always "Id" + NavigationPropertyName)? If you just want the foreign key for a single entity you will be better off just using the ForeignKey
attribute:
public class Guru
{
public int Id { get; set; }
public int? IdKotaLahir { get; set; }
[ForeignKey("IdKotaLahir")]
public virtual Kota KotaLahir { get; set; }
}
这适用于 EF5 和 EF6.在 EF6 中,您可以使用自定义约定来配置外键属性.这是我想出的自定义约定:
This will work for both EF5 and EF6. In EF6 you can use custom conventions to configure foreign key properties. Here is custom convention I came up with:
public class NavigationPropertyConfigurationConvention
: IConfigurationConvention<PropertyInfo, NavigationPropertyConfiguration>
{
public void Apply(
PropertyInfo propertyInfo, Func<NavigationPropertyConfiguration> configuration)
{
var foreignKeyProperty =
propertyInfo.DeclaringType.GetProperty("Id" + propertyInfo.Name);
if (foreignKeyProperty != null && configuration().Constraint == null)
{
var fkConstraint = new ForeignKeyConstraintConfiguration();
fkConstraint.AddColumn(foreignKeyProperty);
configuration().Constraint = fkConstraint;
}
}
}
我还写了一个更详细的关于此的博文.
I also wrote a more detailed blog post on this.
这篇关于实体框架 6 自定义关系约定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:实体框架 6 自定义关系约定


- WebMatrix WebSecurity PasswordSalt 2022-01-01
- 在哪里可以找到使用中的C#/XML文档注释的好例子? 2022-01-01
- C# 中多线程网络服务器的模式 2022-01-01
- 带有服务/守护程序应用程序的 Microsoft Graph CSharp SDK 和 OneDrive for Business - 配额方面返回 null 2022-01-01
- 如何用自己压缩一个 IEnumerable 2022-01-01
- MoreLinq maxBy vs LINQ max + where 2022-01-01
- 输入按键事件处理程序 2022-01-01
- C#MongoDB使用Builders查找派生对象 2022-09-04
- 良好实践:如何重用 .csproj 和 .sln 文件来为 CI 创建 2022-01-01
- Web Api 中的 Swagger .netcore 3.1,使用 swagger UI 设置日期时间格式 2022-01-01