我发现的大多数问题都不是我要找的类型。
我有两张桌子:
public class User
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid UserId { get; set; }
public Guid? CustomerId { get; set; }
[ForeignKey("CustomerId")]
public Customer Customer { get; set; }
}
public class Customer
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid CustomerId { get; set; }
public Guid? UserId { get; set; }
[ForeignKey("UserId")]
public User User { get; set; }
}
User
可以存在而不是Customer
而Customer
可以存在而不是User
。
我尝试了这样流畅的API:
modelBuilder.Entity<Customer>()
.HasOptional<User>(c => c.User)
.WithOptionalDependent(c => c.Customer)
.Map(c => c.MapKey("UserId"));
但是当我尝试创建迁移时,它一直给我这个错误:
Customer_User_Source: : Multiplicity is not valid in Role 'Customer_User_Source' in relationship 'Customer_User'. Because the Dependent Role properties are not the key properties, the upper bound of the multiplicity of the Dependent Role must be '*'.
更新
我将模型改为:
public class User
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid UserId { get; set; }
public virtual Customer Customer { get; set; }
}
public class Customer
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid CustomerId { get; set; }
public virtual User User { get; set; }
}
使用流畅的API:
modelBuilder
.Entity<Customer>()
.HasOptional(l => l.User)
.WithOptionalPrincipal()
.Map(k => k.MapKey("CustomerId"));
modelBuilder
.Entity<User>()
.HasOptional(c => c.Customer)
.WithOptionalPrincipal()
.Map(k => k.MapKey("UserId"));
这似乎有效,但有没有办法在模型中定义列而不必使用MapKey
?