13

Here's my situation: I have been working on an ASP.NET MVC 3 application for a while. It has a database (built out of a db project; I'm going db-first) for which I have an edmx model and then a set of POCOs. My entities have plural names in the database and POCOs have singular names. Everything maps nicely without a problem.

Or used to until I added a new table (called TransactionStatuses). Now all of the old entities still work but the new one does not. When I try to eagerly load it together with a related entity:

var transactions = (from t in db.Transactions.Include(s => s.TransactionStatus) //TransactionStatus - navigation property in Transactions to TransactionStatuses
                    where t.CustomerID == CustomerID
                    select t).ToList();

I get

Invalid object name 'dbo.TransactionStatus'.

I even did a simpler test:

List<TransactionStatus> statuses = db.TransactionStatuses.ToList();

= same result.

I have updated (and even re-created) edmx from the db and have gone through it back and forth trying to figure out what is different about the mapping for dbo.TransactionStatus*es* which trips the whole thing up.

If somebody can point me in the direction of a fix it'd be wonderful.

P.S. Turning off pluralisation is not an option, thanks.

Update: I figured it out - my answer below.

abatishchev
  • 98,240
  • 88
  • 296
  • 433
Dmitry Selitskiy
  • 633
  • 1
  • 5
  • 16
  • can you create a new instance of TransactionStatuses ? If so look at the outbound sql that EF is generating and be sure that it is specifying the correct table. – BentOnCoding Feb 25 '12 at 08:39
  • That is the problem, SQL has the singular name... and I am trying to figure out why and how to fix it. – Dmitry Selitskiy Feb 25 '12 at 09:35

4 Answers4

32

This is probably happening because even though the intention was to use the Database First flow, in actual fact the application is using Code First to do the mapping. Let me explain a bit more because this can be confusing. :-)

When using Database First with the EF Designer and the DbContext templates in Visual Studio three very important things happen. First, the new Entity Data Model wizard adds a connection string to your app containing details of the Database First model (i.e. the EDMX) so that when the application is run it can find this model. The connection string will look something like this:

<connectionStrings>
    <add name="MyEntities"
    connectionString="metadata=res://*/MyModel.csdl|res://*/MyModel.ssdl|res://*/MyModel.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=.\sqlexpress;initial catalog=MyEntities;integrated security=True;multipleactiveresultsets=True;App=EntityFramework&quot;"
    providerName="System.Data.EntityClient" />
</connectionStrings>

Second, the generated context class makes a call to the base DbContext constructor specifying the name of this connection string:

public MyEntities()
: base("name=MyEntities")
{
}

This tells DbContext to find and use the "MyEntities" connection string in the config. Using "name=" means that DbContext will throw if it doesn't find the connection string--it won't just go ahead and create a connection by convention.

If you want to use Database First, then you must use a connection string like the one that is generated. Specifically, it must contain the model data (the csdl, msl, ssdl from the EDMX) and you must make sure that DbContext finds it. Be very careful when changing the call to the base constructor.

The third thing that happens is that OnModelCreating is overridden in the generated context and made to throw:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    throw new UnintentionalCodeFirstException();
}

This is done because OnModelCreating is only ever called when using Code First. This is because OnModelCreating is all about creating the model, but when you are using Database First the model already exists--there is nothing to create at runtime. So if OnModelCreating is called then it is probably because you started using Code First without meaning to, usually because of a change to the connection string or the call to the base constructor.

Now, it might be that you want to use Code First to map to an existing database. This is a great pattern and fully supported (see http://blogs.msdn.com/b/adonet/archive/2011/03/07/when-is-code-first-not-code-first.aspx) but you will need to make sure mappings are setup appropriately for this to work. If the mappings are not setup correctly then you will get exceptions like the one in this question.

Arthur Vickers
  • 7,503
  • 32
  • 26
  • OK I see! this is great, I'll go back to check these steps but I think I am missing the reference to correct connection string in DbContext constructor! Which would mean that it is happening code-first. I'll update on my findings. – Dmitry Selitskiy Feb 26 '12 at 23:18
  • 1
    Yes, this is definitely it. I did have the correct connection string in my DAL project but not in my MVC app project (where I had an ordinary connection string). I attempted to change this according to the points you raised but I started getting the UnintentionalCodeFirstException and I cannot figure out what is calling it... in summary, thank you very much for clarifying this. This is the first time I see a clear cut distinction of set up between Code First and DB first. – Dmitry Selitskiy Feb 27 '12 at 04:49
7

Got it! Horrible, horrible experience...

In short: EF cannot correctly pluralize entity names that end with "s" (e.g. "status", "campus", etc.)

Here's how I got it and proof.

  • I've created and re-created my original set up several times with the same result.
  • I also tried renaming my table to things like TransStatus and the like - no luck.
  • While I was researching about this I came across the pluralization article by Scott Hanselman where he added pluralization rules for words like sheep and goose. This got me thinking "what if he problem is in the actual name of the entity?"
  • I did some searching about the word status in particular and found this report of the problem on Connect. I rushed to try renaming my entity...
  • Renaming TransactionStatuses to TransactionStates (while even keeping the columns as StatusID) fixed the issue! I can now get List<TransactionState> statuses = db.TransactionStates.ToList();
  • I thought the problem was with the particular word status in the name... But after vocally complaining about this to a friend I was suggested that maybe the problem is with the word ending with "s"... So I decided to check it out.
  • I set up another table called Campuses and matching POCO Campus (and updated the edmx). Did the simple test List<Campus> test = db.Campuses.ToList(); and got the now expected

Invalid object name 'dbo.Campus'.

So there you go, the mighty EF cannot handle pluralization of words ending with "s". Hopefully, the next poor bugger hitting the problem will find this question and save him- or herself 3-4 hours of pain and frustration.

Ben
  • 54,723
  • 49
  • 178
  • 224
Dmitry Selitskiy
  • 633
  • 1
  • 5
  • 16
  • 4
    EF does not use it's pluralization service for naming the database. It only uses it for naming the entityset in the model which becomes the objectset (or dbset) in your context class. If you do database first, EF knows the name of your table becaue it's getting the info directl from the database. In EDMX by default it will do it's best job to create a pluralized entityset name from teh entity. But then it's mapping file says that that entityset maps to whatever table name it saw in teh db when you created the model – Julie Lerman Feb 25 '12 at 23:33
  • 1
    and the pluralization service is definitely limited. I agree about that. But I am not understanding how that has anything to do with the database table name. – Julie Lerman Feb 25 '12 at 23:37
  • I know that, thanks. And as I said in EDMX everything looks ok, e.g. table name "xStatuses" and matching class "xStatus". But when it generates the SQL it looks for "dbo.xStatus" in the db even though _it read out of the db into edmx_ that the table name is "xStatuses". Try the campus example I gave and you will see it happen. – Dmitry Selitskiy Feb 25 '12 at 23:38
  • In dutch we have a word "Inkomen" which means "income" but the pluralizer turns it into "Inkoman" lol – rfcdejong Feb 26 '12 at 00:04
  • Dmitry, okay I believe you! :) But what you are seeing doesn't make any sense to me at all so I'm frustrated.I think there's a piece of information that I'm missing that will explain this behavior. But I'll let it go, if you are satisfied with your workaround. :) – Julie Lerman Feb 26 '12 at 01:06
  • @JulieLerman I am not satisfied, to be honest... I'd rather have the names I want. So if you think you can get to the bottom of this with more info - ask away and I'll try to answer to the best of my abilities. – Dmitry Selitskiy Feb 26 '12 at 01:41
  • 2
    Dmitry, here's a short camtasia of the default behavior that should normally be happening. At least you'lls ee why I'm confused by your problem. Watch that and then we can look at your db/model/profiler to see why you're getting a different experience. (I didn't touch any of the defaults) http://dl.dropbox.com/u/13420868/dmitrys.mp4 (there's no sound) – Julie Lerman Feb 26 '12 at 13:40
  • @Dmitry Can you override OnModelCreating in your context and see if it ever gets called when you run your app? (i.e. Make it throw an exception or something.) If it does get called, then you're not really using database first and what you are seeing would make sense based on Code First mapping to an existing database. If it doesn't get called then I agree with Julie that this behavior is extremely strange and I'd love to see a full repro. – Arthur Vickers Feb 26 '12 at 20:55
  • @JulieLerman Thanks! Video makes total sense except for the part of not seeing the POCOs.. Did you let the edmx generate those for you? In my case I use my own, not generated. – Dmitry Selitskiy Feb 26 '12 at 21:20
  • @ajcvickers Good point. I'll try this (not in front of my dev machine atm). Something tells me though that OnModelCreating gets called because I remember mapping couple of 1-1 relationships there... I think I'm becoming more confused now. – Dmitry Selitskiy Feb 26 '12 at 21:26
  • 1
    @JulieLerman see answer by ajcvicker, he got me going in the correct direction and it now probably eliminates your confusion. However, technically the answer still stands: Pluralization Service cannot pluralise "Status" and "Campus" :) – Dmitry Selitskiy Feb 27 '12 at 04:51
  • 1
    @DmitrySelitskiy...I respectfully disagree with your proposed answer. it's absolutely true that the pluralization service can't pluralize status & campus but [unless something changed in EF code first that I'm unaware of] the pluralization services is not used for database table naming...only for entityset naming. And your problem was with the database name, not the entityset name. It *looked* like pluralization was causing this problem but it was not involved. :) Code FIrst was following it's convention to expect a table name that matches the entity name. – Julie Lerman Feb 27 '12 at 17:38
0

Sigh. Same type of an issue with the class and model Photo and Video; it is looking for the table Photoes and Videoes. I hate to just change the table name, but not much of a choice it looks like.

drewid
  • 2,737
  • 3
  • 16
  • 11
0

You mention EDMX but I can't tell if you are doing databse first with EDMX or code first and just using EDMX to see what's going on.

If you are using Code First, then you can use a configuration to specify the table name. Data Annotation is [Table("TransactionStatuses")], fluent is modelBuilder.Entity().ToTable("TransactionStatuses"). (I'm typing the annotation and fluent code from memory so double check references. ;) )

If you are using database first, the SSDL should absolutely be aware of the name of the database table, so I'm guessing that you are using code first & the edmx is just for exploration. (???)

hth

Julie Lerman
  • 4,602
  • 2
  • 22
  • 21