5

我有 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 一个 Exemption。我如何在 EF Core 1.0 中做到这一点?

4

1 回答 1

4

您将需要显式添加外键:

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 代码,因此您也可以对所有其他注释使用 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);
于 2017-01-24T14:34:58.500 回答