Entity Framework Code first mapping without foreign key

后端 未结 1 528
长情又很酷
长情又很酷 2020-12-17 00:20

I have two tables:

Requirement

  • ID (int) PK
  • ClientID (int)
  • JobNumber (int)

Comment

  • ID (int) PK
相关标签:
1条回答
  • 2020-12-17 00:53

    It's not possible. With Entity Framework the entity that the Comment.Requirement navigation property is refering to is generally identified by the (primary) key property in Requirement, i.e. by ID. There is no mapping option to define that the target property is anything else than the key property - like JobNumber or another non-key property.

    I could only imagine that you could "fake" the primary key property in the model to be JobNumber instead of ID (given that JobNumber is unique in the Requirement table):

    modelBuilder.Entity<Requirement>().HasKey(r => r.JobNumber);
    

    I don't know if that could have other unwished side effects. (For sure it doesn't work if JobNumber is not unique because EF wouldn't allow to have more than one entity with the same key attached to a context and updates/deletes and so on wouldn't find the correct record in the database.) It feels wrong and hacky to me. I honestly wouldn't even try that, live with the fact that you don't have a real foreign key relationship in the database, forget the navigation properties Requirement.Comments and Comment.Requirement and use manual joins in LINQ to relate the table data/entities as I need them in a given situation.

    0 讨论(0)
提交回复
热议问题