2017-04-25 61 views
0

我试图做一个简单的数据插入我的数据库,但我得到以下错误:“无效的对象名称dbo。”。C#实体框架错误:无效的对象名称'dbo.TableName'

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

我插入代码:

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

+0

哪个表名称不存在(在单台或内部数据库中的所有表)和抛绳错误?我看到你正在尝试Code First Migrations,它可能与表格关系有关,或者被称为“多元化”。 –

+0

把你得到的错误细节和你得到它的时刻。同时添加实体模型视图。 –

回答

0

尝试加入这一行你的代码。

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

你的部分类tb_alunos不具有[表(“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; } 

} 
相关问题