EF代码优先 – 1对1可选关系
我想用EF Code First在现有数据库中映射可选的1对1关系。
简单的模式:
User Username ContactID Contact ID Name
ContactIDjoinContact.ID显然。 ContactID字段为空,所以关系是可选的 – 0或1,从不多。
那么如何在EF Code First中用这个现有的模式来指定这个关系呢?
以下是我迄今为止所尝试的:
public class User { [Key] public string Username { get; set; } public int? ContactID { get; set; } [ForeignKey("ContactID")] public virtual Contact Contact { get; set; } } public class Contact { [Key] public int ID { get; set; } public string Name { get; set; } public virtual User User { get; set; } } modelBuilder.Entity<User>().HasOptional<Contact>(u=> u.Contact) .WithOptionalDependent(c => c.User);
我得到以下exception:
System.Data.Edm.EdmAssociationEnd: : Multiplicity is not valid in Role 'User_Contact_Source' in relationship 'User_Contact'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be *.
一个解决scheme是;
public class User { [Key] public string Username { get; set; } public virtual Contact Contact { get; set; } } public class Contact { [Key] public int ID { get; set; } public string Name { get; set; } public virtual User User { get; set; } } modelBuilder.Entity<User>() .HasOptional<Contact>(u => u.Contact) .WithOptionalDependent(c => c.User).Map(p => p.MapKey("ContactID"));
您只在POCO中设置导航对象,而使用stream畅的API将您的密钥映射到正确的列。