如何外键财产暴露在有使用EF6代码第一次航行性能现有实体 [英] How to expose Foreign Key property to existing entity having navigational property using EF6 Code First

查看:381
本文介绍了如何外键财产暴露在有使用EF6代码第一次航行性能现有实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有已经被与下面的数据库中使用的实体,并用只是导航属性创建可选的实体(1:0..1)。因此,通过默认的约定,EF创建一个数据库中的可为空的外键列,并把它与下划线MyProp_Id的名称,根据该公约。

I have an entity which is already being used with an underlying database, and it was created with just the navigational property to an optional entity (1:0..1). So by default conventions, EF created a nullable foreign key column in the DB and gave it the "MyProp_Id" name with underscore, according to that convention.

现在,我想揭露外键作为实体的属性,因为它会使某些情况下对我来说更容易。我不想重命名/在DB(该MyProp_Id一个)改变底层外键列。其实,不应该有任何基础数据库的更新,我只是想揭露了FK的实体。一个代码示例,以澄清:

Now, I wish to expose that foreign key as a property on the entity, because it will make certain scenarios easier for me. I don't want to rename/change the underlying foreign key column in the DB (the MyProp_Id one). In fact, there shouldn't be any underlying DB updates, I just want to expose that FK on the entity. A code sample to clarify:

public class MyEntityA 
{
    public long Id { get; set; }

    //public long? MyOptionalEntityB_Id { get; set; }  <== this is what I am trying to add
    //public long? MyOptionalEntityBId { get; set; }  <== this didn't work either

    public MyEntityB MyOptionalEntityB { get; set; }

}



我试过只是简单地添加MyOptionalEntity_Id财产上的实体属性,希望EF会自动地看到,由于该名称是相同的,它只是地图和快乐。没有骰子。

I've tried just simply adding the "MyOptionalEntity_Id" property as property on the entity, hoping that EF would "automagically" see that because the names are the same, it would just map and be happy. NO DICE.

然后我试图说出我的财产MyOptionalEntityId(无下划线),但仍然没有骰子。

Then I tried to name my property "MyOptionalEntityId" (no underscore), but still NO DICE.

然后我试图加入一个明确的映射配置的说:

Then I tried adding an explicit mapping configuration to say:

this.Property(p => p.MyOptionalEntityId).HasColumnName("MyOptionalEntity_Id");

没有DICE

有没有办法去做这个?这是明确的和有意义吗?

Is there a way to do this? Is this clear and make sense?

推荐答案

尝试添加的外键属性

public long? MyOptionalEntityB_Id { get; set; }
[ForeignKey("MyOptionalEntityB_Id")]
public MyEntityB MyOptionalEntityB { get; set; }

或使用的流畅API

 modelBuilder.Entity<MyEntityA >()
    .HasOptional(x => x.MyOptionalEntityB)
    .WithMany().HasForeignKey(x => x.MyOptionalEntityB_Id);
          // ^^^ -> if MyEntityB has collection of MyEntityA, mention it

这篇关于如何外键财产暴露在有使用EF6代码第一次航行性能现有实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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