Change model after database is created on EF4 code only - entity-framework-4

Hey, sorry for my bad english...
Using EF4 code-only, I have created some POCO classes and my database was generated from that. All worked fine, I inserted some data on the tables but now I need to create a new property on one of my classes. If i just create it, the application give me the exception:
{"The model backing the 'TestContext' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance. For example, the RecreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data."}
I tried to create manually the field on the table, but it is still complaining... does someone know if there is a way and if so how can I manually update the database schema (i don't want to recreate it because i already have data) to match the model?

It should work if you make sure that your new column match exactly your new property.
For example, if you add a property NewProp
public class MyEntity
{
[Key]
public int Id;
public string PropA;
public int PropB;
public int NewProp;
}
then in your database table MyEntities, you would add a column NewProp of type int not null.
What you can do to check if the column you add is correct, is to rename your database, then let Code-First recreate the database and see what's different between the original and new databases.

EF generates partial classes. So you can add new properties(fields) in another partial class.

Related

How can I create and use views using EF6 Code First?

Is there actually any official strategy for creating and using views with EF6.1 Code First? I can reverse the database into Code First and get tables not views. I can import the database into Model First and get views and then do Generate DB from Model and my edmx is modified and the views are converted to tables. MSFT seems to have all but abandoned Model First, and the new Update 2 seems to have reverse engineering for Code First so I feel forced to convert to Code First but has the EF team given support for any reasonable approach to using views or stored Procedures in Code First? After all CF is supposed to create the DB but what - are you no longer supposed to use either of these SQL Server features in a .NET EF application?
For starters you can use views and stored procedures that are already created in the database. For views you don't have to do any mapping if you create a code like this:
public TestContext : DbContext
{
public DbSet<User> AdminUsers { get; set; }
}
And you have a view in the database named dbo.AdminUsers and it can be mapped to the class User (contains all required properties with the same name as the property).
For stored procedures you can use the SqlQuery function either through the Database property of the DbContext such as:
var userActivityReport = context.Database.SqlQuery<UserActivityReport>(
"dbo.GetUserActivityReport #p0, #p1", startDate, endDate);
Or through the SqlQuery function of the DbSet class:
var newUsers = context.Users.SqlQuery("dbo.GetNewUsers #p0", count);
If you want to create, modify or delete views and stored procedures via Entity Framework you can either use custom migration operations see http://dolinkamark.wordpress.com/2014/05/03/creating-a-custom-migration-operation-in-entity-framework/
For event better integration you can use the Public mapping API with a library provided by a community member: https://codefirstfunctions.codeplex.com/

Can't create MVC4 controller for classes with a base class (Generated from Entity Framework)

I am using Entity Framework 5 with MVC4 to create a small test-app using Model First.
I have two projects, a data project, and a ui project which references data.
I have my model MYModel.edmx in data which has the following entity's
[ITEM]
[BOOK][DVD]
Where "book" and "dvd" have a base type of the abstract class "Item".
Using the code-generation, it creates the classes for these 3 tables and my dbContext as so:
public DbSet<Item> Items {get;set;}
Not creating any DbSet for accessing "Books" or "DVDs".
IF I try to create a new controller using my data context and a model class of "Books" I get the following error
mynamespace.data.books is not part of the specified mynamespace.data.dbcontext class, and the mynamespace.data.dbcontext class could not be modified to add a dbset<mynamespace.data.books> property to it. (For example )
What is the correct way to go about using EF with base types and model first as I am clearly doing something wrong, should I even be using Model first? Would it be easier to use Code first for this scenario and create the DBContext myself?
I'm not terribly familiar with model-first, but try adding this in your mynamespace.data namespace:
public class DVD : Item{
//Put your DVD specific properties here
}
public class Book : Item{
//Put your Book specific properties here
}
Don't add primary keys here, they will both inherit the ItemId primary key, because in the database both DVD and Book are being stored in the Item table.
Then, add the two models to your context:
public DbSet<DVD> DVDs {get;set;}
public DbSet<Book> Books {get;set;}
A good reference to implementing Table-Per-Hierarchy via code-first can be found here, I'm sorry i don't know of any model-first reference: http://www.asp.net/mvc/tutorials/getting-started-with-ef-using-mvc/implementing-inheritance-with-the-entity-framework-in-an-asp-net-mvc-application
I had a same problem, but I don't know what causes it. All you need to do is:
Compile the project
Right click your Controllers folder to add your controller
In Data Context class, Add Controller dialog box, manually type your context, and click Add
Hope it help

Asp mvc 3 noobie: Why is the code-first method not building my DB on sql server?

I am an ASP MVC 3 noobie who has done a few tutorials. Now I'm trying to build a site. All of the tutorials on the microsoft website emphasize the code-first approach: you define your model with code and then create a datacontext and then the entity framework creates/manages the DB based on your code.
I set up an Employees class and a DataBaseContext class that inherits from DbContext. I added a connection string to Web.config connection string that successfully links DataBaseContext to an already existing empty DB on SQL server. EDIT= That was the problem. See my answer below
But when I try to run the Employees controller created thru scaffolding, I get this error
Invalid object name 'dbo.Employees'.
Description: An unhandled exception occurred during the execution of...
Exception Details: System.Data.SqlClient.SqlException: Invalid object name 'dbo.Employees'.
I followed this post SqlException (0x80131904): Invalid object name 'dbo.Categories' and realized that if I create an employees table on the DB, this excpetion goes away (I get a new one saying that the column names are invalid).
But I thought the whole point of MVC 3 is that the framework will make the DB for you based on the code.
Maybe I need a line of code in the Global.asax Application_start() to create the database? Here is my application_start method:
Sub Application_Start()
AreaRegistration.RegisterAllAreas()
RegisterGlobalFilters(GlobalFilters.Filters)
RegisterRoutes(RouteTable.Routes)
End Sub
Here is the code for Employee:
Public Class Employee
Property EmployeeID As Integer
Property First As String
Property Last As String
Property StartDate As DateTime
Property VacationHours As Integer
Property DateOfBirth As DateTime 'in case two employees have the same name
End Class
Here is the code for the DB context:
Imports System.Data.Entity
Public Class DatabaseContext
Inherits DbContext
Public Property Employee As DbSet(Of Employee)
Public Property AnnualLeave As DbSet(Of AnnualLeave)
End Class
What am I missing?
By default EF uses DropCreateDatabaseIfModelChanges<TContext> database initializer. Accordingly to the MSDN:
An implementation of IDatabaseInitializer<TContext> that will delete, recreate, and optionally re-seed the database with data only if the model has changed since the database was created. This is achieved by writing a hash of the store model to the database when it is created and then comparing that hash with one generated from the current model.
Since the database was created manually, EF can't find the hash and decides do not perform any further initialization logic.
You might want to look into this article, same question successfully answered already.
Or it can be this (also resolved successfully)
Answer to your problem is most likely one of the two.
Hope this will help you
Does the name you're specifying for your connection string match the name of your database context?
For example:
Context
var myDbContext = new MyDbContext();
Connection string
<connectionStrings>
<add name="MyDbContext" connectionString="YOUR.CONNECTION.STRING" providerName="System.Data.SqlServer" />
</connectionStrings>
Try and see if this post I wrote about DbContext with MVC works for you: Code-First
Not a lot to be done to get this to work, but there are a few things that are easily missed that will cause a bunch of head aches.
hope this helps
I had already created a database with that name on SQL server. Once I deleted the existing database, the code first framework created the tables for me like it was supposed to. It seems like if the database already exists, the framework won't set up the tables for you. It wants to create the whole DB from scratch.
You were using AdventureWorks Database?
It has it's own schema assigned to the employees table. HumanResources.Employees and not the default dbo.Employees.
Even though I've identified the problem, I don't know the solution to using the database as configured with the HumanResources schema.
Anybody know?

MVC Trouble Deleting a record

I get an error when trying to delete a record:
InvalidOperationException - The object cannot be deleted because it was not found in the ObjectStateManager.
public ActionResult Delete(CustomerModel customer)
{
db.Customer.Remove(customer);
db.SaveChanges();
return View();
}
Update: I checked in the bebugger, customer is completely empty..And therefore the database isn't able to delete that specific record.
Any ideas why?
Your customer object was not loaded into the DbContext called db (I'm assuming it's a DbContext... not entirely clear from your code).
With Entity Framework, the DbContext you are using has to be aware of an object it is acting on. It looks like you created customer in some manner other than by loading it into db.
You can add it to the DbContext like this:
db.Attach(customer);
Then, proceed to remove it and save your changes.
For more details see
http://blogs.msdn.com/b/adonet/archive/2011/01/29/using-dbcontext-in-ef-feature-ctp5-part-4-add-attach-and-entity-states.aspx
Specifically for your case the paragraph Attaching an existing entity to the context
Update (based on your update)
How did you create customer in the first place? Without that detail, it's just guesswork to understand why it's completely empty.

How to refresh my database

I was creating an mvc application and i had a model class with a dbcontext function the variables were in the same file. I added another field and changed the code in the edit create delete details and index views but i now get an error saying
"The model backing the 'GameDBContext' context has changed since the database was created. Either manually delete/update the database, or call Database.SetInitializer with an IDatabaseInitializer instance. For example, the DropCreateDatabaseIfModelChanges strategy will automatically delete and recreate the database, and optionally seed it with new data."
Imports System.Data.Entity
Public Class Game
Public Property ID() As Integer
Public Property Name() As String
Public Property Genre() As String
Public Property Price() As Decimal
Public Property Developer() As String
End Class
Public Class GameDBContext
Inherits DbContext
Public Property Games() As DbSet(Of Game)
End Class
you need to add a initializer method to the Application_Start method in Global.asax file. Ex:-
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<GameDBContext>());
Since it sounds like you're using a code first approach in developing your application, here are a couple of links that might help you:
code first development with entity framework 4
Code First/Entity Framework 4.1 Videos and Articles on MSDN
All of these can give you a better understanding of what is happening and how to work around having your database change on you.
In short, since you added another property, the entity framework table in your database is now longer in sync with your class. Since it's no longer in sync, you must manually delete this database in order to regenerate it, or you must create an initialization for the database. All of these concepts are better described in the links I have provided.
Good luck, and hope these help you some.

Resources