实体框架1到1的设置关系 [英] setup relation for 1 to 1 with entity framework
问题描述
如何设置ContactId的建模工具?
How do I have to setup the modelbuilder for the ContactId?
CountryCompanyAssignment与联系人有关系。
A CountryCompanyAssignment has a relation to a Contact.
当我删除CountryCompanyAssignment时,我不想让联系人丢失。
When I delete the CountryCompanyAssignment I do not want that the contact is lost.
当我创建CountryCompanyAssignment时,我还需要一个联系人来保存CountryCompanyAssignment。
When I create a CountryCompanyAssignment then I also need a contact to save the CountryCompanyAssignment.
我需要设置CountryCompanyAssignment和ContactId之间的关系,因为当我删除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.
这是我试过的:
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; }
推荐答案
如果您使用WithRequired,必须是FK:
if you use a WithRequired, one of the PK must be a FK:
- Contact.Id如果WihtRequiredPrincipal
- Company.Id如果WithRequiredDependent
-
- Contact.Id if WihtRequiredPrincipal
- Company.Id if WithRequiredDependent
如果您想要公开并选择您必须的fk:
if you want to expose and choose the fk you must:
modelBuilder.Entity<Company>().HasRequired(x => x.Contact). WithMany().HasForeignKey(y => y.ContactId);
这篇关于实体框架1到1的设置关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!