简体   繁体   English

具有自定义外键和FK属性的EF6流利关系

[英]EF6 fluent relation with custom foreign key and FK property

I'm trying to migrate existing project to EF and already have strict database structure and mandatory set of properties. 我正在尝试将现有项目迁移到EF,并且已经具有严格的数据库结构和强制性的属性集。 The problem I now fight with is on the following. 我现在要解决的问题是以下问题。

I have two classes: 我有两节课:

public class Entity
{
    public virtual long ID {get;set;}
    public virtual long ContragentID {get;set;}
    public virtual Contragent {get;set;}
}

public class Contragent
{
    public virtual long ID {get;set;}
    public virtual long EntityID {get;set;}
    public virtual Entity {get;set;}
}

With the following entity mappings: 使用以下实体映射:

    public class ClassContragentAccountMap : EntityTypeConfiguration<Contragent>
{
    public ClassContragentAccountMap()
    {
        // Primary Key
        HasKey(t => t.ID);
        // Table & Column Mappings
        ToTable("contragent");
        Property(t => t.ID).HasColumnName("id");        
        Property(t => t.EntityID).HasColumnName("e_id");    

        HasOptional(t => t.Entity).WithOptionalDependent(t => t.Contragent);
    }
}

public class ClassLegalEntityAccountMap : EntityTypeConfiguration<Entity>
{
    public ClassLegalEntityAccountMap()
    {
        // Primary Key
        HasKey(t => t.ID);

        // Table & Column Mappings
        ToTable("entity");
        Property(t => t.ID).HasColumnName("id");
        Property(t => t.ContragentID).HasColumnName("contragentid");
    }
}

The problem is that relation throws an exception that Entity_ID column is not found. 问题是该关系引发了一个异常,即找不到Entity_ID列。 Is there a way to specify FK for the relation as attributes seems to not work here? 有没有一种方法可以为关系指定FK,因为属性似乎在这里不起作用? I've also tried to use: 我也尝试使用:

HasOptional(t => t.Entity).WithOptionalDependent(t => t.Contragent).Map(t=> t.MapKey("e_id"));

But then it conflicts with the already defined 'e_id' property. 但是,这与已经定义的'e_id'属性冲突。 And I need both relation and the property present. 而且我需要联系和财产。

Is there any way to specify FK for relation and preserve ID properties in classes? 有什么方法可以为关系指定FK并在类中保留ID属性吗?

Probably I can go with remaking relation ID properties: 也许我可以重新构建关系ID属性:

public virtual long ContragentID => Contragent?.ID;

public virtual long EntityID => Entity?.ID;

But I want to know is there any other way to do it. 但我想知道还有其他方法可以做到这一点。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM