'propertyName'不能用作实体类型 'typeName' 的属性,因为它配置为导航



我有一个实体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时,我得到错误:

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

我试图在导航属性上创建一个索引。相反,在外键上创建索引。

user.HasIndex(x => x.Gender)更改为user.HasIndex(x => x.GenderId)

由于类似问题而进行的更新:

当我在产品实体和担保主体之间建立关系时,我遇到了同样的问题,如下所示:

public class Product
{
public long Id { get; set; }
public string Images { get; set; }
public string Brand { get; set; }
public Warranti Warranti { get; set; }
}

public class Warranti
{
public Product Product { get; set; }
public long ProductId { get; set; }
public int WarrantyPeriod { get; set; }
}

在我的DatabaseContext类上,我有这样的配置:

protected override void OnModelCreating(ModelBuilder modelBuilder)  
{
modelBuilder.Entity<Product>()
.HasOne(p => p.Warranti)
.WithOne(p => p.Product)
.HasForeignKey<Warranti>(p => p.Product);
}

我也犯了同样的错误。但是,问题出在哪里?

根据微软官方EFCore文档,ForeignKey应该是这样的:

.HasForeignKey(p => p.BlogForeignKey); // single prop such as string or int,...

.HasForeignKey("BlogForeignKey"); // Hardcoded favorite string

但我使用的是a class(Product),而不是HasForeignKey方法中的一个属性。同样,您使用的是a class(Gender),而不是属性InHasIndex方法。将这些类更改为Id属性可以解决问题。

作为结论:尝试在HasForeignKey((和HasIndex((上使用Id属性;

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

希望它能解决你的问题。

谢谢,

我有一个类似的错误:

"产品"不能用作实体类型"OrderLine"的属性因为它被配置为导航。

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

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

对于嵌套复杂类的复杂层次结构模型,我也遇到了同样的问题。
显然,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();
}
}

相关内容

最新更新