“字段列表”中存在未知列“s.ManagerGroup_id”

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

我正在使用 MySql 数据库开发毛伊岛应用程序。当我第一次与数据库交互时,出现异常: “ System.Exception:‘字段列表’中的未知列‘s.ManagerGroup_id’” 我正在使用 ORM 标签。

    [Table("ManagerGroups")]
    public class ManagerGroup
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int ManagerGroup_id {  get; set; }

        [Required]
        [Column(TypeName = "char(100)")]
        public required string Name { get; set; }

        public List<Manager> Managers { get; set;} = new List<Manager>();

        public List<Staff> AssignedStaff { get; set;} = new List<Staff>();
    }
public class MyDbContext : DbContext
{
    public MyDbContext(DbContextOptions<MyDbContext> options) : base(options)
    {
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        // Configure logging directly within OnConfiguring
        var loggerFactory = LoggerFactory.Create(builder =>
        {
            builder.AddConsole().SetMinimumLevel(LogLevel.Information); // Add console logging provider
        });

        optionsBuilder.UseLoggerFactory(loggerFactory); // Configure logging
        var logger = loggerFactory.CreateLogger<MyDbContext>();
        logger.LogWarning("Logger Ready!");
    }

    // DbSet properties for your database entities
    //public DbSet<MyEntity> MyEntities { get; set; }
    public DbSet<User> Users { get; set; }
    public DbSet<Manager> Managers { get; set; }
    public DbSet<Staff> Staff { get; set; }
    public DbSet<SoS_AnswerSheet> SoS_AnswerSheets { get; set; }
    public DbSet<Staff_SoSList> Staff_SoSLists { get; set; }
    public DbSet<ManagerGroup> ManagerGroups { get; set; }
    // Add more DbSet properties for other entities if needed



    //Junction Table config for composite keys
    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<Staff_SoSList>()
            .HasKey(e => new { e.ManagerGroup_id, e.Staff_id });


        //SoS_AnswerSheet Enum mapping to int
        #region SoS_AnswerSheet Enum mapping
        modelBuilder.Entity<SoS_AnswerSheet>()
            .Property(e => e.Answer1)
            .HasConversion<int>();

        modelBuilder.Entity<SoS_AnswerSheet>()
            .Property(e => e.Answer2)
            .HasConversion<int>();

        // Configure other enum properties similarly
        modelBuilder.Entity<SoS_AnswerSheet>()
            .Property(e => e.Answer3)
            .HasConversion<int>();

        modelBuilder.Entity<SoS_AnswerSheet>()
            .Property(e => e.Answer4)
            .HasConversion<int>();

        modelBuilder.Entity<SoS_AnswerSheet>()
            .Property(e => e.Answer5)
            .HasConversion<int>();

        modelBuilder.Entity<SoS_AnswerSheet>()
            .Property(e => e.Answer6)
            .HasConversion<int>();

        modelBuilder.Entity<SoS_AnswerSheet>()
            .Property(e => e.Answer7)
            .HasConversion<int>();

        modelBuilder.Entity<SoS_AnswerSheet>()
            .Property(e => e.Answer8)
            .HasConversion<int>();

        modelBuilder.Entity<SoS_AnswerSheet>()
            .Property(e => e.Answer9)
            .HasConversion<int>();

        modelBuilder.Entity<SoS_AnswerSheet>()
            .Property(e => e.Answer10)
            .HasConversion<int>();

        modelBuilder.Entity<SoS_AnswerSheet>()
            .Property(e => e.Answer11)
            .HasConversion<int>();

        modelBuilder.Entity<SoS_AnswerSheet>()
            .Property(e => e.Answer12)
            .HasConversion<int>();

        #endregion

    }
}

我检查了数据库中的所有表,名称正确且与应用程序中的表匹配。 我尝试通过记录 sql 查询来解决这个问题,但我无法让记录器工作。 请考虑我是数据库新手。如果需要的话,很乐意提供更多信息。

错误日志:

Microsoft.EntityFrameworkCore.Database.Command: Error: Failed executing DbCommand (27ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT `u`.`User_id`, `u`.`CreatedAt`, `u`.`First_name`, `u`.`Last_name`, `m`.`Manager_id`, `s`.`ManagerGroup_id`, `s`.`staff_id`, CASE
    WHEN `s`.`User_id` IS NOT NULL THEN 'Staff'
    WHEN `m`.`User_id` IS NOT NULL THEN 'Manager'
END AS `Discriminator`
FROM `Users` AS `u`
LEFT JOIN `Managers` AS `m` ON `u`.`User_id` = `m`.`User_id`
LEFT JOIN `Staff` AS `s` ON `u`.`User_id` = `s`.`User_id`
'WaiterEval.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.4\System.Diagnostics.StackTrace.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'WaiterEval.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.4\System.Reflection.Metadata.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
'WaiterEval.exe' (CoreCLR: clrhost): Loaded 'C:\Program Files\dotnet\shared\Microsoft.NETCore.App\8.0.4\System.IO.Compression.dll'. Skipped loading symbols. Module is optimized and the debugger option 'Just My Code' is enabled.
Microsoft.EntityFrameworkCore.Query: Error: An exception occurred while iterating over the results of a query for context type 'WaiterEval.Services.MyDbContext'.
MySqlConnector.MySqlException (0x80004005): Unknown column 's.ManagerGroup_id' in 'field list'

这是 Aql 查询抛出错误的错误日志。

c# maui
1个回答
0
投票

数据库是现有的,不是通过迁移创建的。对于遇到同样问题的每个人,只需检查 EF 是否为 List 生成了联结表,但在您的数据库中名称不同。 就我而言,它是通过以下方式解决的:

    [Table("ManagerGroups")]
    public class ManagerGroup
    {
        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int ManagerGroup_id {  get; set; }
        // This creates a junction table with Staff
        public List<Staff> AssignedStaff { get; set;} = new List<Staff>();
    }
}
    [Table("Staff")]
    public class Staff : User
    {
        [DatabaseGenerated(DatabaseGeneratedOption.None)]
        [ForeignKey("User")]
        public int staff_id
        {
            get => User_id;
            set => User_id = value;
        }
        //Option 1 to fix:
        public List<ManagerGroup> managergroups { get; set;} = new List<ManagerGroup>();
    }

将其添加到 MyDbContext 类

//Option 1:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<ManagerGroup>()
        .HasMany(mg => mg.AssignedStaff)
        .WithMany(s => s.ManagerGroups)
        .UsingEntity(j => j.ToTable("ManagerGroups_AssignedStaff"));
}
//Option 2: (add a new class to represent the junction table)
public DbSet<ManagerGroup_AssignedStaff> ManagerGroups_AssignedStaff { get; set; }
modelBuilder.Entity<ManagerGroupAssignedStaff>()
    .HasKey(e => new { e.ManagerGroup_id, e.Staff_id });

对于选项 2,您还需要一个新课程

using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;

namespace WaiterEval.Models
{
    [Table("ManagerGroups_AssignedStaff")]
    public class ManagerGroupAssignedStaff
    {
        [Key]
        [Column(Order = 1)]
        public int ManagerGroup_id { get; set; }

        [Key]
        [Column(Order = 2)]
        public int Staff_id { get; set; }

    }
}
© www.soinside.com 2019 - 2024. All rights reserved.