代码之家  ›  专栏  ›  技术社区  ›  Danial Ahmed

System.Data.SqlClient客户端.SqlException:列名“Gender\u id”无效

  •  1
  • Danial Ahmed  · 技术社区  · 6 年前

    我正在学习Web应用程序开发asp.netmvc和实体框架。我有一个数据库,有3个表,分别是学生、性别和课程。我遇到了这个问题。

    错误在第23行。

    列名“Genders\u Id”无效。

    异常详细信息: 列名“Programs\u Id”无效。

    Source Error:
    
    
    Line 21:         {
    Line 22:             StudentsContext stdContext = new StudentsContext();
    Line 23:             Students students = stdContext.Students.Single(std => std.Id == id);
    Line 24:             //ViewBag.Student = students;
    Line 25:             return View(students);
    

    namespace WebApplication4.Models
    {
      public class Students
      {
         public string Name { get; set; }
         public int Id { get; set; }
         public int Gender { get; set; }
         public int Program { get; set; }
         public string Country { get; set; }
       }
    }
    

    public class StudentsContext:DbContext
    {
        public DbSet<Students> Students { get; set; }
        public DbSet<Programs> Programs { get; set; }
        public DbSet<Genders> Genders { get; set; }
    }
    

    public class Programs
    {
        public int Id { get; set; }
        public string Program { get; set; }
        public List<Students> Students { get; set; }
    }
    

    public class Genders
    {
        public int Id { get; set; }
        public string Gender { get; set; }
        public List<Students> Students { get; set; }
    }
    

    数据库表:

    enter image description here

    2 回复  |  直到 6 年前
        1
  •  8
  •   Ivan Stoev    6 年前

    Genders_Id Programs_Id Genders.Students Programs.Students 集合导航属性。

    [ForeinKey] 数据注释:

    public class Programs
    {
        // ...
        [ForeignKey("Program")]
        public List<Students> Students { get; set; }
    }
    
    public class Genders
    {
        // ...
        [ForeignKey("Gender")]
        public List<Students> Students { get; set; }
    }
    

    或者(我的首选)fluent API:

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        // ...
    
        modelBuilder.Entity<Genders>()
            .HasMany(e => e.Students)
            .WithRequired()
            .HasForeignKey(e => e.Gender);
    
        modelBuilder.Entity<Programs>()
            .HasMany(e => e.Students)
            .WithRequired()
            .HasForeignKey(e => e.Program);
    }
    
        2
  •  1
  •   Mati Ullah Zahir    6 年前

    数据层中的连接字符串和web层中的连接字符串指向不同的数据库。

    e、 数据层读取dev数据库webapp指向测试数据库。