gpt4 book ai didi

c# - 系统.Data.SqlClient.SqlException : Invalid column name 'Gender_id'

转载 作者:太空宇宙 更新时间:2023-11-03 19:41:57 24 4
gpt4 key购买 nike

我正在学习使用 asp.net mvc 和 Entity Framework 开发 Web 应用程序。我有一个包含 3 个表格学生、性别和类(class)的数据库。我遇到了这个问题。

错误在第 23 行。

Invalid column name 'Genders_Id'. Invalid column name 'Programs_Id'.

Exception Details: System.Data.SqlClient.SqlException: Invalid column name 'Genders_Id'. Invalid column name 'Programs_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);

我的 Students.cs 模型代码:

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

我的 Context.cs 文件:

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

程序.cs:

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

性别.cs:

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

数据库表:

enter image description here

最佳答案

Genders_IdPrograms_Id 是 FK 列的默认 EF6 约定名称,用于分别由 Genders.StudentsPrograms.Students 集合导航属性。

由于您的 FK 属性/列名不是常规名称,您应该通过 [ForeinKey] 数据注释来指定它们:

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

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

或(我的首选)流畅的 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);
}

关于c# - 系统.Data.SqlClient.SqlException : Invalid column name 'Gender_id' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52237800/

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