使非原始属性的组合在 Entity Framework 中独一无二

Making a combination of non-primitive properties unique in Entity Framework

有谁知道如何使用 Entity Framework 的代码优先方法将另一个 class 作为多列唯一索引的一部分?

我希望将所有人员的 ExternalId 和 PersonCategory.Id 的组合设为唯一,以便数据库中同一对 "ExternalId" 和 [= 只能存在一个人员19=]。关于如何实现此行为的任何想法?

我尝试使用索引注释,但这导致只有 ExternalId 唯一,类别 属性 被忽略。

public class Person
{
    public int Id { get; set; }

    [Required]
    [Index("IX_Person_PersonCategory", 1, IsUnique = true)]
    [MaxLength(100)]
    public string ExternalId { get; set; }

    [Required]
    [Index("IX_Person_PersonCategory", 2, IsUnique = true)]
    public PersonCategory Category { get; set; }

    ...
}

public class PersonCategory
{
    public int Id { get; set; }

    ...
}

您不能将唯一索引(存在于数据库中)添加到导航 属性(这是一个 EF 元素)。索引必须在用于 link Person 和 PersonCategory 的实际外键中。

为了对其进行配置,您需要在 Person 实体中明确定义 PersonCategoryId。

public class Person
{
    public int Id { get; set; }

    [Required]
    [Index("IX_Person_PersonCategory", 1, IsUnique = true)]
    [MaxLength(100)]
    public string ExternalId { get; set; }

    [Index("IX_Person_PersonCategory", 2, IsUnique = true)]
    public int CategoryId { get; set; }

    public PersonCategory Category { get; set; }

    ...
}