gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 15:26:32 25 4
gpt4 key购买 nike

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

'Gender' cannot be used as a property on entity type 'User' because it is configured as a navigation.

最佳答案

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

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

关于c# - 'propertyName' 不能用作实体类型 'typeName' 的属性,因为它被配置为导航,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58659431/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com