实体框架 6 自定义关系约定 [英] Entity Framework 6 Custom Relationship Convention

查看:23
本文介绍了实体框架 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 自定义关系约定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆