Thiago Silva
Thiago Silva

Reputation: 17691

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

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?

Upvotes: 2

Views: 2281

Answers (1)

Yuliam Chandra
Yuliam Chandra

Reputation: 14640

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

Upvotes: 3

Related Questions