asp.net core 在两列上创建约束,其中一列是另一个实体

asp.net core create a constraint on two columns, one of which is another entity

我有 2 个 类(实体)豁免和期间,我想用豁免的 IdNumber 和期间的 Id 创建一个唯一索引

     public class Exemption
        {
            [Key]
            public int Id { get; set; }
            [Required]
            public string FirstName { get; set; }
            .
            .
            .
            [Required]
            public string IdNumber { get; set; }
            [Required]
            public Period Period { get; set; }
         }

     public class Period
        {
            [Key]
            public int Id { get; set; }
            .
            .
            .
            [Required]
            public string Year { get; set; }

         }

使用 Fluent API 我在 OnModelCreating 中添加了 .HasIndex 但出现错误

builder.Entity<Exemption>().HasIndex(c => new { c.IdNumber, c.Period }).IsUnique();

添加迁移时出现如下错误

The properties expression 'c => new <>f__AnonymousType5`2(IdNumber = c.IdNumber, Id = c.Period.Id)' is not valid. The expression should represent a property access: 't => t.MyProperty'. When specifying multiple properties use an anonymous type: 't => new {  t.MyProperty1, t.MyProperty2 }'.

我尝试添加 c.Period.Id

 builder.Entity<Exemption>()
                    .HasIndex(c => new { c.IdNumber, c.Period.Id }).IsUnique();

出现以下错误

The property 'Period' cannot be added to the entity type 'Exemption' because a navigation property with the same name already exists on entity type 'Exemption'.

我只需要允许每个 IdNumber 有一个豁免 Period.Id 我如何在 EF Core 1.0 中执行此操作?

您需要显式添加外键:

public class Exemption
{
   [Key]
   public int Id { get; set; }
   [Required]
   public string FirstName { get; set; }
   .
   .
   .
   [Required]
   public string IdNumber { get; set; }
   [Required]
   public int PeriodId { get; set; }
   [ForeignKey("PeriodId")]
   public Period Period { get; set; }
}

然后就可以索引了:

builder.Entity<Exemption>().HasIndex(c => new { c.IdNumber, c.PeriodId }).IsUnique();

此外,由于您对索引使用 fluent api code,因此您也可以对所有其他注释使用 fluent。例如:

builder.Entity<Exemption>()
       .HasKey(c => c.Id)
       .HasIndex(c => new { c.IdNumber, c.PeriodId })
       .IsUnique();

builder.Entity<Exemption>().Property(p => p.FirstName)
       .IsRequired()          
       .HasMaxLength(100);