2

I have a project where i use EF 4.1.

At Data Context:

 public DbSet<Customer> Customer { get; set; }       
 protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)      {            }

Entity model class:

[Table("User",SchemaName="dbo")]
public class User{  
public int Id { get; set; }  
public string FirstName { get; set; }  
public string LastName { get; set; } 
}

Once I run the application I was getting following error.

Invalid object name dbo.User

Why? What is wrong?

Dave Anderson
  • 23
  • 1
  • 3

2 Answers2

5

What is in your OnModelCreating method?

Try to remove default plural table name:

modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
Dana Addler
  • 973
  • 8
  • 4
1

If you happen to be using configuration mapping (EntityTypeConfiguration) classes to define your tables, you'll get this error if you forget to attach the Configuration class for the table to the Model Builder.

In my case, it really stumped me for a bit, because I already had another table (SomeThing) working perfectly within this Context class. After simply adding a new table (OtherThing) where everything seemed to be setup identical to the first, I got the error: Invalid object name 'dbo.OtherThings.

The answer was in my Context class:

public DbSet<SomeThing> SomeThings { get; set; }
public DbSet<OtherThing> OtherThings { get; set; }

...

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Configurations.Add(new SomeThingMap());

    // OOPS -- Forgot to add this!!
    modelBuilder.Configurations.Add(new OtherThingMap());
}

For reference, here's my SomeThingMap class:

public class SomeThingMap : EntityTypeConfiguration<SomeThing>
{
    public SomeThingMap()
    {
        ...

        this.ToTable("SomeThing");

        ...
    }
}

And my new OtherThingMap class:

public class OtherThingMap : EntityTypeConfiguration<OtherThing>
{
    public OtherThingMap()
    {
        ...

        this.ToTable("OtherThing");

        ...
    }
}

It's a long shot, but I hope this helps point someone else in the right direction, at least.

Brian Lacy
  • 18,785
  • 10
  • 55
  • 73
  • I have tried unsuccessfully to use `ToTable` and also annotations but i still keep getting this error.For more info check my [post](https://stackoverflow.com/questions/59352944/invalid-object-name-error-when-creating-database-with-ef-code-first) – Bercovici Adrian Dec 16 '19 at 13:15
  • Add schema name like -> this.ToTable("TableName", "SchemaName") – Aetos2501 Jun 11 '21 at 15:14