c# - 如何基于自定义属性添加一对多关系

标签 c# entity-framework foreign-keys entity-framework-core

假设我有两个实体:

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 上?

最佳答案

这是可能的,但前提是 CustomerCustomerKey 属性(列)是唯一的。这是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/

相关文章:

mysql - 强制两个一对一表之间的唯一性

c# - 从非执行可执行文件中获取版本

c# - 如何在 C# 中制作一个不可见但可点击的按钮

c# - 使用 Streamreader.Read block /RedirectStandardOutput

c# - 用于存储过程执行的通用包装器

asp.net-mvc - EntityFramework 到 Json 的解决方法? (在序列化 ...DynamicProxies 类型的对象时检测到循环引用)

mysql - Hibernate 具有外键名称的多对一键

c# - 找不到类型或命名空间名称 `UnityEditor'

c# - 值 xxx 对 yyy 无效。错误的日期时间格式

database - Firebird 1.5.3 : How to add FK with connected users to the DB?