当您有两个表需要一个第三个表作为参考,而第三个表不能单独存在时,如何建立关系模型,如下所示:
`User` has an `Address`
`Shop` has an `Address`
An `Address` can either belong to a `Shop` or to a `User` , but it can't exist on its own.
User and Shop must not be modelled as derived entities from a superclass (in code) since they got nothing in common
下面的方法是使用来自这两者的外键 User
以及 Shop
但是我不喜欢这种方法,因为我不想让所有使用 Address
内部 Address
有没有其他方法来保持 Address
班级 clean
?
public class Address
{
public long Id{get;set;}
[ForeignKey(nameof(User)]
public long? UserId{get;set;}
[ForeignKey(nameof(Shop)]
public long? ShopId{get;set;}
public class User User {get;set;}
public class Shop Shop {get;set;}
}
public class User
{
public long Id{get;set;}
[InverseProperty(nameof(Address.User)]
public long AddressId {get;set;}
public Address Address {get;set;}
}
public class Shop
{
public long Id{get;set;}
[ForeignKey(nameof(Address.Shop)]
public long AddressId {get;set;}
public Address Address {get;set;}
}
在fluent api中,它类似于:
modelBuilder.Entity<Address>().HasOne(y=>y.User).WithOne(z=>z.Address).OnDelete(Cascade);
modelBuilder.Entity<Address>().HasOne(y=>y.Shop).WithOne(z=>z.Address).OnDelete(Cascade);
永远不会有这样的情况 Address
两者都有 User
以及
Shop NOT NULL
暂无答案!
目前还没有任何答案,快来回答吧!