Entity Framework Core:无法确定关系错误

问题描述 投票:0回答:1

我目前正在使用 Entity Framework Core 开发 .NET Core 项目,并且遇到与配置两个实体

Advertisement 
ApplicationUser
之间的关系相关的问题。

以下是这些类的简化结构:

public class Advertisement
{
    [Key]
    public Guid Id { get; init; }
    [Required]
    public Guid ApplicationUserId { get; set; }
    [Required]
    public ApplicationUser ApplicationUser { get; set; }
    // Other properties...
}

public class ApplicationUser : IdentityUser<Guid>
{
    [Required]
    public string CompanyName { get; init; }
    [Required]
    public string UserType { get; init; }
    [Required]
    public bool IsAdvertiser { get; init; } = false;
    public ICollection<Advertisement> Advertisements { get; set; }
    public ICollection<Advertisement> SavedAdvertisements { get; set; }
}

我尝试使用 Fluent API 在我的

OnModelCreating
DbContext
方法中配置关系,如下所示:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    modelBuilder.Entity<Advertisement>()
        .HasOne(a => a.ApplicationUser)
        .WithMany(u => u.Advertisements)
        .HasForeignKey(a => a.ApplicationUserId);
}

但是,我仍然收到错误消息:

无法确定“ApplicationUser”类型的导航“Advertisement.ApplicationUser”表示的关系。手动配置关系,或者使用“[NotMapped]”属性或使用“OnModelCreating”中的“EntityTypeBuilder.Ignore”忽略此属性

我已经检查了命名空间、

DbContext
注册以及此错误的其他常见来源,但我无法解决它。

有人可以提供有关如何使用 Entity Framework Core 正确配置这两个实体之间的关系的指导吗?

使用的版本:

  • Microsoft.EntityFrameworkCore 7.0.12
  • Microsoft.AspNetCore.Identity.EntityFrameworkCore 7.0.12
asp.net-core entity-framework-core asp.net-identity
1个回答
0
投票

也许也可以尝试添加逆关系,这应该有助于 EF 理解这种关系。

modelBuilder.Entity<ApplicationUser>()
        .HasMany(u => u.Advertisements)
        .WithOne(a => a.ApplicationUser)
        .HasForeignKey(a => a.ApplicationUserId);
© www.soinside.com 2019 - 2024. All rights reserved.