2017-04-25 62 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; } 

} 
相關問題