【问题标题】:'propertyName' cannot be used as a property on entity type 'typeName' because it is configured as a navigation“propertyName”不能用作实体类型“typeName”的属性,因为它被配置为导航
【发布时间】:2020-02-27 18:18:26
【问题描述】:

我有一个实体user,具有以下内容:

public class User
{
    [Key, Required]
    public int Id { get; set; }
    public int GenderId { get; set; }
    public virtual Gender Gender { get; set; }
}

gender:

public class Gender
{
    [Key, Required]
    public int Id { get; set; }
    public virtual ICollection<User> Users { get; set; }
}

然后,在我的DbContext 中,我有:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<User>(user =>
    {
        user
        .HasOne(x => x.Gender)
        .WithMany(x => x.Users)
        .HasForeignKey(x => x.GenderId);
    }

    user.HasIndex(x => x.Gender);
}

当我运行 dotnet ef add migration User 时,我收到了错误:

“性别”不能用作实体类型“用户”的属性,因为它 配置为导航。

【问题讨论】:

  • 错误不能来自所示的型号和配置。您的真实代码中必须有其他内容,例如.Property(x =&gt; x.Gender) 或类似内容。
  • 对不起。我错过了在实际导致问题的问题中添加一点代码。 user.HasIndex(x =&gt; x.Gender); 我试图在导航属性上创建索引。我不得不把它改成user.HasIndex(x =&gt; x.GenderId);

标签: c# asp.net entity-framework asp.net-core entity-framework-core


【解决方案1】:

我试图在导航属性上创建索引。而是在外键上创建索引。

user.HasIndex(x =&gt; x.Gender) 更改为user.HasIndex(x =&gt; x.GenderId)

【讨论】:

    【解决方案2】:

    在您的 public virtual Gender Gender { get; set; } 属性上使用 [ForeignKey("GenderId")]。因此,GenderId 将被标识为关联用户的外键。

    见下面更新的代码:

    public class User
    {
        public int GenderId { get; set; }
        [ForeignKey("Id")]//Gender Primary key
        public virtual Gender Gender { get; set; }
    }
    

    希望它能解决您的问题。

    谢谢,

    【讨论】:

    • .HasForeignKey(x =&gt; x.GenderId); 里面的DbContext 不做同样的事情吗?
    【解决方案3】:

    我遇到了类似的错误:

    “Product”不能用作实体类型“OrderLine”的属性 因为它被配置为导航。

    错误的原因是在fluent api中我还使用了实体作为属性:

    modelBuilder.Entity<OrderLine>().Property(ol => ol.Product).IsRequired(true)
    

    【讨论】:

      【解决方案4】:

      对于包含嵌套复杂类的复杂层次模型,我遇到了同样的问题。
      显然,IsRequired() 方法与OnDelete(...) 冲突。我删除了IsRequired(),一切都恢复正常了。

      public class MyComplexClassConfig : IEntityTypeConfiguration<MyComplexClass>
      {
          public void Configure(EntityTypeBuilder<MyComplexClass> builder)
          {
              builder
                  .HasOne(col => col.ChildClass)
                  .WithOne(col => col.ParentClass)
                  .OnDelete(DeleteBehavior.Cascade);
                  
              // The following line of code needs to be deleted.
              builder.Property(col => col.Customer).IsRequired();
          }
      }
      

      【讨论】:

        猜你喜欢
        • 2021-12-19
        • 2019-01-10
        • 1970-01-01
        • 1970-01-01
        • 2018-07-31
        • 1970-01-01
        • 2018-03-31
        • 1970-01-01
        • 2022-12-23
        相关资源
        最近更新 更多