How to expose Foreign Key property to existing entity having navigational property using EF6 Code First

谁说胖子不能爱 提交于 2019-12-20 04:52:32

问题


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.

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; }

}

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.

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");

NO DICE

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


回答1:


Try adding foreign key attribute.

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

Or using fluent api.

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


来源:https://stackoverflow.com/questions/25061378/how-to-expose-foreign-key-property-to-existing-entity-having-navigational-proper

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!