我有以下课程:
User, Address, UserAddress
public class User
{
public ICollection<useraddress> userAddresses { get; set; }
}
public class Address
{
public virtual User User { get; set; }
public virtual Guid UserId { get; set; }
public UserAddress UserAddress { get; set; }
}
public class UserAddress
{
public User User { get; set; }
public Guid UserId { get; set; }
public Address Address { get; set; }
public Guid AddressId { get; set; }
}
我在UserAddressConfig
中创建了以下流畅的配置:
HasKey(row => new { row.UserId,row.AddressId});
和AdddressConfig
:
HasOptional(row => row.UserAddress).WithRequired(row => row.Address).WillCascadeOnDelete();
答案 0 :(得分:1)
你可以用这个:
public class User
{
public Guid Id { get; set; }
[InverseProperty("User")]
public ICollection<UserAddress> UserAddresses { get; set; }
}
public class Address
{
public Guid AddressId { get; set; }
public UserAddress UserAddresses { get; set; }
}
public class UserAddress
{
public Guid AddressId { get; set; }
public Address Address { get; set; }
[ForeignKey("UserId")]
[InverseProperty("UserAddresses")]
public User User { get; set; }
public Guid UserId { get; set; }
}
并配置流畅的api:
modelBuilder.Entity<Address>().HasRequired(c => c.UserAddress)
.WithOptional(c => c.Address) // or any other option
.WillCascadeOnDelete(false);
但您也可以在用户和地址之间建立一对多关系,如下所示:
public class User
{
public Guid Id { get; set; }
[InverseProperty("User")]
public ICollection<Address> Addresses { get; set; }
}
public class Address
{
public Guid AddressId { get; set; }
[ForeignKey("UserId")]
[InverseProperty("Addresses")]
public User User { get; set; }
public Guid UserId { get; set; }
}