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

后端 未结 1 1470
庸人自扰
庸人自扰 2021-01-25 01:43

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 c

相关标签:
1条回答
  • 2021-01-25 02:05

    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
    
    0 讨论(0)
提交回复
热议问题