实体框架 6 自定义关系约定

Entity Framework 6 Custom Relationship Convention(实体框架 6 自定义关系约定)
本文介绍了实体框架 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 自定义关系约定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)