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 自定义关系约定


基础教程推荐
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01