I created an MVC 4 application using EF (Code First) which mapped to a mixture of tables and views which I created using SQL Management Studio which worked fine.
I have started a new MVC 4 project in much the same way as the first, using a completely different database, but this time anytime I try to use a model which maps to a view (not a table), an exception is raised saying that "An object with the name xxx already exists". The SQL profiler shows that EF is trying to create a table for my model.
I find that if I drop the views, let EF create the tables from the models, then delete the tables and replace them with view manually, the application will work for about 2 minutes, reading and using the information from my view, but eventually throwing the same exception.
I have no idea what is going on here.
The code that causes the exception is:
repository.Customers.OrderBy(c => c.AccountNumber);
where the model is:
public class Customer
{
public int Id {get;set;}
public string AccountNumber {get;set;}
public string Name {get;set;}
}
OK - the possible cause of this issue is hiding in your context file. There is probably a statement similar to the one below that is trying to update your database when the model changes.
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Database.SetInitializer<MyContext>(new DropCreateDatabaseIfModelChanges<MyContext>());
}
I generally don't use this method. I prefer to delete the database and re-generate it using the package manager console. (Check out the update-database method of the package manager console)
Using Greg's hint I was able to arrive at the point where I simply added:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
Database.SetInitializer<MyContext>(null);
}
to the context class and this has solved the issue. My understanding here is that I have told EF to do no initialisation, essentially having it map to an existing database that is maintained outside of the code first context.
I have voted up Greg's response as it was the help I needed but creating a new answer as it was the above that solved it eventually. I hope this was done right.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.