setup relation for 1 to 1 with entity framework

↘锁芯ラ 提交于 2019-12-25 08:56:34

问题


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

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