Dave Anderson
Dave Anderson

Reputation: 23

Entity framework - Invalid Object Name

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?

Upvotes: 2

Views: 8046

Answers (2)

Brian Lacy
Brian Lacy

Reputation: 19118

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.

Upvotes: 1

Dana Addler
Dana Addler

Reputation: 983

What is in your OnModelCreating method?

Try to remove default plural table name:

modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

Upvotes: 5

Related Questions