【问题标题】:asp.net core create a constraint on two columns, one of which is another entityasp.net core在两列上创建一个约束,其中一个是另一个实体
【发布时间】:2017-06-09 06:56:09
【问题描述】:

我有 2 个类(实体)Exemption 和 Period,我想用来自豁免的 IdNumber 和来自 Period 的 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 中做到这一点?

【问题讨论】:

    标签: .net entity-framework asp.net-core ef-code-first ef-code-first-mapping


    【解决方案1】:

    您需要显式添加外键:

    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);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-05
      • 1970-01-01
      • 2021-03-17
      • 1970-01-01
      • 2016-08-31
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多