C# - 实体框架错误:无效的对象名称'dbo.TableName'

时间:2017-04-25 06:04:08

标签: c# sql-server entity-framework

我正在尝试在我的数据库上进行简单的数据插入,但是我收到了以下错误:“无效的对象名称dbo。”。

导入(我认为)详细信息...我在另一个测试中做了基本相同的代码,但是我使用Sql Management Studio创建了表和数据库。现在,我刚刚使用Empty EF Designer模型在visual studio中创建。

我的插入代码:

private void button1_Click(object sender, EventArgs e)
{
    try
    {
        using (AlunoModelContainer ctx = new AlunoModelContainer()) { 
            tb_alunos student = new tb_alunos();

        student.nome_aluno = textBox1.Text;
        student.idade_aluno = textBox2.Text;
        student.curso_aluno = textBox4.Text;
        student.endereco_aluno = textBox5.Text;

        ctx.Alunos.Add(student);
        ctx.SaveChanges();
        MessageBox.Show("Estudante cadastrado com sucesso");
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("Usuário não pôde ser cadastrado." + ex.ToString());
    }

}

我的数据库上下文代码:

namespace Sistema_Alunos
{
    using System;
    using System.Data.Entity;
    using System.Data.Entity.Infrastructure;

    public partial class AlunoModelContainer : DbContext
    {
        public AlunoModelContainer()
            : base("name=AlunoModelContainer")
        {
        }

        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }

        public virtual DbSet<tb_alunos> Alunos { get; set; }
    }
}

我的文件夹结构的简单图像:

enter image description here

3 个答案:

答案 0 :(得分:1)

尝试将此行添加到您的代码中。

 protected override void OnModelCreating(DbModelBuilder modelBuilder)
 {
      modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
 }

答案 1 :(得分:0)

您的部分类tb_alunos没有[Table(“tb_alunos”)]属性,因此无法映射到数据库表。

试试这个:

 [Table("tb_alunos")]
public partial class tb_alunos
{
    public int alunoID { get; set; }
    public string nome_aluno { get; set; }
    public string curso_aluno { get; set; }
    public string endereco_aluno { get; set; }
    public string idade__aluno { get; set; }

}

答案 2 :(得分:0)

我找到了解决此问题的方法。我有同样的问题。我已经创建了名为SubscriptionType的表,但是在按照约定创建表时,Entity Framework在表名的末尾添加了额外的“ S”,因此它变成了SubscriptionTypes

因此,请在数据库和模型类中匹配表名。