假设我有两个实体:
public class Customer
{
public int CustomerId { get; set; }
public Guid CustomerKey { get; set; }
public ICollection<Product> Products { get; set; }
}
public class Product
{
public int ProductId { get; set; }
public Guid CustomerKey { get; set; }
public string Name { get; set; }
}
1 个客户可以拥有许多产品,但我想根据 CustomerKey
属性绑定(bind)它们。以下是示例数据的示例:
CustomerId | CustomerKey
1 | {00000000-0000-0000-0000-111111111111}
2 | {00000000-0000-0000-0000-222222222222}
ProductId | Name | CustomerKey
1 | Product1 | {00000000-0000-0000-0000-111111111111}
2 | Product2 | {00000000-0000-0000-0000-111111111111}
3 | Product3 | {00000000-0000-0000-0000-222222222222}
因此,第一个客户拥有前两种产品,第二个客户拥有最后一个产品。我尝试做类似的事情:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>().HasMany(m => m.Products);
}
但是我如何指定要将它们绑定(bind)到 CustomerKey
上?
最佳答案
这是可能的,但前提是 Customer
的 CustomerKey
属性(列)是唯一的。这是EF Core的要求(实际上是关系数据库FK要求,但EF Core仅支持可以表示为关系数据库FK约束的关系),所以如果不是,那么您所要求的就是不可能的。
流畅的 API 是 HasPrincipalKey
方法:
Configures the unique property(s) that this relationship targets. Typically you would only call this method if you want to use a property(s) other than the primary key as the principal property(s). If the specified property(s) is not already a unique constraint (or the primary key) then a new unique constraint will be introduced.
当然,FK 照常配置为 HasForeignKey
.
将其应用到您的模型:
modelBuilder.Entity<Customer>()
.HasMany(customer => customer.Products)
.WithOne() // no navigation property
.HasForeignKey(product => product.CustomerKey)
.HasPrincipalKey(customer => customer.CustomerKey);
关于c# - 如何基于自定义属性添加一对多关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52164249/