Wednesday, October 12, 2011

Code first in Entity Framework database not being created

There are a few excelent resources on the web that help a great deal as tutorials for the Entity Framework but many are a version too old-ish.
If your connection string is correct, if the contact class and DbSet class code correct, and if the project has a reference to the correct version of EntityFramework, and the database is still not being created, here are a few pointers to look for.

(But, do look at the date of this post and versions as this will be out of date quite soon.)

One thing to look for:
If you think you have created the context class correctly, and web config strings, then close the ASP.NET development server icon in the icon tray. If this server is running, it seems that Code First will be prevented from creating a new database. There may be multiple instances of this server loaded. Simply STOP them down and then re-run your project. Then check the database.

Another thing to look for:
Check that CFCodefirst.1.1 is in the Packages folder. You will probably need to look of this in the file system at the root of the project / solution . Also check that it is entered in the packages.config file.
Something like:

<package id="EntityFramework" version="4.1.10331.0" />
<package id="EFCodeFirst" version="1.1" />

Make sure that you ask for some values from the database context. That is, use a property.
And, make sure the return value is correct. If the property fetch fails, you may not know about it. It'll fail and you'll get no data + you won't get your database made. I suggest you use:

var model = _db.DummyBooks;


Also,
If you have the data code in its own project, for some kind of layering. Then beware of giving the Entities the same name as other Domain objects. I know this is vague advice, but if you name the Entitiy something like Customer, and if there is a Domain object called Customer, then the Code First might get confused and fail to create the database. It often does this without telling you why.

If all else fails,
Sometime Visual Studio and the SQL Server Management Studio just seem to play up. They say the database isn't there, sometimes it's not. Sometimes putting a breakpoint after the call to the Context property seems to work. It seems random. But, if you go step by step, from the simplest to adding more and more complexity, shutting down VS and the db connection, progress can be had.
I'm sure this nightmare doesn't always happen. As yet I don't know what causes it.

No comments:

Post a Comment