MVC and Entity Framework's Code First

I have a new web application project and decided to use MVC 4 and Entity Framework's Code First. I'll post here the problems encountered and how I fixed it.

MVC has option for automatic scaffolding when creating the CRUD functionality, but when I tried to execute it, I got the following error.

Invalid value for key 'attachdbfilename'.

I've searched the net for an hour and never found the solution. Though my connection string is working correctly, I decided to take a second look at the web.config and seen this peculiar line of setting. So I commented the LocalDBConnectionFactory and replaced with System.Data.Entity.Sql.ConnectionFactory instead so it will use the connection string on parameter. It fixed my problem.

<entityframework>
    <defaultconnectionfactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework">
    <!--<defaultconnectionfactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework" >-->
      <parameters>
        <parameter value="Data Source=USER-PC\SQLServer;Initial Catalog=MyDB;Integrated Security=True"></parameter>
      </parameters>
    </defaultconnectionfactory>
</entityframework>

Entity Framework has this inherent problem whenever it needs to check Model changes, and it won't drop/create the target table, when you want to save. The following error, where 'dbContext' is your defined DB Context.


The model backing the 'dbContext' context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).

To solve this problem in CRUD, you need to add the following code on your corresponding controller constructor.

Add this -> System.Data.Entity.Database.SetInitializer(null);


 public MyControllerController() : this(new MyModel())
        {
            System.Data.Entity.Database.SetInitializer(null);
        }

Or if it's in a unit testing, add it under constructor, e.g.


[TestClass]
public class UnitTestDB
{

public UnitTestDB()
{
System.Data.Entity.Database.SetInitializer(null);

No comments:

Post a Comment