Chr*_*ini 26 one-to-one ef-code-first
我想使用EF Code First在现有数据库中映射可选的1对1关系.
简单架构:
User
Username
ContactID
Contact
ID
Name
Run Code Online (Sandbox Code Playgroud)
显然ContactID加入了Contact.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);
Run Code Online (Sandbox Code Playgroud)
我得到以下例外:
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 *.
Run Code Online (Sandbox Code Playgroud)
Per*_*Per 42
一个解决方案是;
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"));
Run Code Online (Sandbox Code Playgroud)
您只在POCO中设置导航对象,而是使用流畅的API将密钥映射到正确的列.
| 归档时间: |
|
| 查看次数: |
28605 次 |
| 最近记录: |