实体框架6客户关系公约 [英] Entity Framework 6 Custom Relationship Convention

查看:85
本文介绍了实体框架6客户关系公约的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已阅读有关规定,这个文档中的实体框架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+ LT; NavigationPropertyName>
是否有可能使用实体框架(EF 6阿尔法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;
        }           
    }
}



我也写了一个更详细的博客文章这一点。

这篇关于实体框架6客户关系公约的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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