问题
How do I have to setup the modelbuilder for the ContactId?
A CountryCompanyAssignment has a relation to a Contact.
When I delete the CountryCompanyAssignment I do not want that the contact is lost.
When I create a CountryCompanyAssignment then I also need a contact to save the CountryCompanyAssignment.
I need to setup the relation between CountryCompanyAssignment and the ContactId because when I delete the CountryCompanyAssignment I get an error saying I should add a foreign key for the Contact to make it work.
This is what I tried:
modelBuilder.Entity<CountryCompanyAssignment>().HasRequired(e => e.Contact).WithRequiredDependent(e => e.);
[Key]
[Column(Order = 1)]
public int Id { get; set; }
[Key]
[Column(Order = 1)]
public string ContactId { get; set; }
[Required]
public string Test{ get; set; }
[Required]
public virtual Contact Contact { get; set; }
回答1:
if you use a WithRequired, one of the PK must be a FK:
- Contact.Id if WihtRequiredPrincipal
- Company.Id if WithRequiredDependent
if you want to expose and choose the fk you must:
modelBuilder.Entity<Company>().HasRequired(x => x.Contact). WithMany().HasForeignKey(y => y.ContactId);
来源:https://stackoverflow.com/questions/29253814/setup-relation-for-1-to-1-with-entity-framework