Invalid object name 'dbo.TableName' when retrieving data from generated table

24,395

Solution 1

To answer your first question: use the schema created for you by your hosting provider.

To answer your second question: No there is currently no direct way to change the default schema globally because you cannot modify existing conventions or create new conventions. You can try to hack it.

For example you can override OnModelCreating and use reflection to get all DbSet<> properties declared in your context. Than you can just use simple loop on these properties and create ToTable mapping call with name of the property as table name and your custom schema. It will require some playing with reflection to make this work.

Alternatively you can try to do some reusable approach by implementing custom conventions. You can find many different articles about using your own conventions with EF. Some examples:

My high level untested idea is following same principle and create assembly level attribute which will be processed by the convention mechanism and applied on all your entities.

Solution 2

Ok, for me issue was that I had a table called dbo.UserState and in C# EF was trying to access dbo.UserStates because of pluralization.

The solution was to put Table attribute above class and specify the exact table name:

[Table("UserState")]
public class UserState
{
    [Key]
    public int UserId { get; set; }
}
Share:
24,395
Jochen van Wylick
Author by

Jochen van Wylick

Solution-focused, analytic and communicative are key characteristics that describe me. I love working in a dynamic environment that is constantly challenging me to find solutions. I can work independently without losing touch with the team and I'm not afraid to take on a leading role. My expertise is IT but I have a broad interest and am very eager to learn and expand my knowledge and skill set.

Updated on May 10, 2020

Comments

  • Jochen van Wylick
    Jochen van Wylick almost 4 years

    I'm using entity framework code first to create my tables. Please note - create the tables, not the DB, since I'm working on a hosted environment and I don't have a user that is allowed to create db's.

    Committing a DB update works fine, but retrieving data gives the exception:

    Exception Details: System.Data.SqlClient.SqlException: Invalid object name 'dbo.EventHosts'.

    I've read that it happens because I'm not using EF Code First to create the DB. That's fine, but how do I elegantly solve this?

    All the generated tables do not have a prefix like dbo. A solution like this doesn't work, and isn't elegant at all:

    [Table("EventHosts", Schema = "")]