Gustavo Dias
Gustavo Dias

Reputation: 135

C# - Entity Framework error: invalid object name 'dbo.TableName'

I'm trying to do a simple data insertion on my database, but I'm getting the follow error: "Invalid Object Name dbo.".

Import(I think) detail... I did basicaly the same code in another test, but I created the table and the db with Sql Management Studio. Now, I just have created in the visual studio using an Empty EF Designer model.

My Insertion code:

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

}

My db context code:

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

And a simple image of my folder structure:

enter image description here

Upvotes: 1

Views: 5547

Answers (3)

Jaydeep Karena
Jaydeep Karena

Reputation: 159

I found the solution for this problem. I have got same problem. I have created table called SubscriptionType but while creating table by convention Entity Framework added extra "S" at the end of table name and it became SubscriptionTypes.

So match your table name in database and in your model class.

Upvotes: 0

KD2ND
KD2ND

Reputation: 321

Your partial class tb_alunos does not have [Table("tb_alunos")] attribute so it cannot be mapped to the table of the database .

Try this :

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

}

Upvotes: 0

samithagun
samithagun

Reputation: 693

Try adding this line to your code.

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

Upvotes: 1

Related Questions