12

We're running into a small problem deploying a web application to another environment. We created the application's db using Entity Framework Code First approach (db automatic created from Model). In this development environment, we are using integrated security and the tables are created under the dbo user. The tables are like
     [dbo].[myTable]

For our other environment, we are using username/password authentication for the DB. We scripted the tables and created them on the DB. So they are now named like
     [myDbUser].[myTable]

When running the application, we encounter always the problem
     Invalid object name 'dbo.myTable'.

Seems like the code is still trying to look for a dbo table, which is not present and thus fails.

Can anyone shed some light on this problem? Where does Entity Framework gets this dbo prefix from?

Thanks

Ronald
  • 1,990
  • 6
  • 24
  • 39

3 Answers3

17

Specify schema explicitly:

[Table("Users", Schema = "dbo")]
public class User { .. }

Or specify default db schema for your user - 'dbo'

Konstantin Tarkus
  • 37,618
  • 14
  • 135
  • 121
  • and how would you do this in Fluent?? (without the attributes) – Ronald Jun 05 '11 at 19:40
  • Littlefool, override OnModelCreating of you database context class and specify mappings there. Here is an example: http://weblogs.asp.net/scottgu/archive/2010/07/23/entity-framework-4-code-first-custom-database-schema-mapping.aspx – Konstantin Tarkus Jun 05 '11 at 19:47
  • I tried that. only thing is that when i debug i see that the code never comes in the OnModelCreating method. i have the impression it's getting the model from some cached source. – Ronald Jun 05 '11 at 20:02
  • never mind. I was modifying an older DbContext in the solution that is no longer used. thanks, you saved my night (or what's left of it) ;) – Ronald Jun 05 '11 at 20:06
  • Also see http://stackoverflow.com/a/7184744/1127033 for more examples. Specifying a default db schema for the SQL Server user didn't work for me, I think it's meant to go the other way--if you're not specifying the user and want it to fill in. – natem345 Jun 06 '12 at 03:31
  • How do you do this for database first?? – SimonGates Nov 15 '12 at 11:14
1

To specify schema in fluent

protected override void OnModelCreating(DbModelBuilder modelBuilder)

modelBuilder.Entity<ClassName>().ToTable("TableName", "SchemaName");
hkutluay
  • 6,794
  • 2
  • 33
  • 53
0

I ran into this issue recently as well as we support several different schemas with the same model. What I basically came up with was the passing the schema name to the classes/methods that map the model. So for example, EntityTypeConfiguration subclasses take the schema name as a constructor argument, and pass it along with the hard-coded string to ToTable().

See here for a more detailed explanation: https://stackoverflow.com/a/14782001/243607

Community
  • 1
  • 1
Anthony Aziz
  • 135
  • 1
  • 7