How to refresh my database - asp.net-mvc

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.

Related

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

EF4 database first configurable schema

I have one issue I am trying to resolve for days now, but I can’t get the right approach.
I am using EF4 and I have one application where I use DataBase First, which originally created the ObjectContext, and I donwloaded the DbContext generator and generated it.
The thing is, I need the application to be able to get the database SCHEMA from some configuration file, instead of ALWAYS using the “dbo” default.
I was trying to use the “ToTable” method (so I can specify the schema) in the “OnModelCreating” overload method but as this article sais, as I am using DataBase First, that method is not called.
How can I make the schema name configurable?
Is that even possible?
I read this article too, where it says I can combine database first with code first but I can’t see how to do that if I can’t use the "OnModelCreating" method.
Thanks a lot in advance!!!
I don't know about configuring schema. However if you want your db first approach to changed to the code first, just change the string parameter of your DbContext constructor.
Suppose that you have the following DbContext that EF Db first created for you:
public class MyDbContext : DbContext
{
public MyDbContext()
: base("Name=DefaultConnection")
{
}
// DbSets ...
}
change that to the following to start using code first and all magic tools of it (migration, etc.):
public class MyDbContext : DbContext
{
public MyDbContext()
: base("YourDbFileName")
{
}
// DbSets ...
}
It causes that EF creates a new connection string using SQL Express on your local machine in your web.config file with the name YourDbFileName, something just like the early DefaultConnection Db first created.
All you may need to continue your way, is that edit the YourDbFileName ConStr according to your server and other options.

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?

ASP.NET MVC Global.asax Shared Property

Is it alright to hang a shared property off of the global.asax (MvcApplication class)?
And then access it like so in other area:
MvcApplication.[SharedPropertyName]
Edit
What I am trying to do is have a globally accessible property that is my application settings.
I am using an XmlSerializer to serialize/deserialize an object that holds all of these properties. It works great, but the Load method on the ApplicationSettings is shared and returns an instance of the ApplicationSettings, so some of the other ideas people have suggested around singelton is not going to work. Here is the ApplicationSettings class:
Public Class ApplicationSettings
#Region "Members/Properties"
Public Property Property1 As String
Public Property Property2 As String
...
#End Region
#Region "Methods"
Public Shared Function GetFilePath() As String
Return HttpContext.Current.Server.MapPath("/Bin/Settings.config")
End Function
Public Shared Function Load() As ApplicationSettings
Try
Dim Serializer As XmlSerializer
Dim Settings As ApplicationSettings
Using Reader As New StreamReader(GetFilePath)
Serializer = New XmlSerializer(GetType(ApplicationSettings))
Settings = CType(Serializer.Deserialize(Reader), ApplicationSettings)
Reader.Close()
End Using
Return Settings
Catch ex As Exception
'Return New ApplicationSettings
Return Nothing
End Try
End Function
Public Sub Save()
Dim Serializer As XmlSerializer
Using Writer As New StreamWriter(GetFilePath, False)
Serializer = New XmlSerializer(GetType(ApplicationSettings))
Serializer.Serialize(Writer, Me)
Writer.Flush()
Writer.Close()
End Using
End Sub
#End Region
End Class
Not recommended. If you need a globally accessible variable or property, that's more suited to a base class that your classes inherit from.
This link gives an example of a controller base class.
EDIT:
Based off your edit, it's tough to recommend something specific because how those settings are used can drive your approach. Here's some general tips:
I'd split out your settings into a series of base classes that are distinct in their area of concern. So settings regarding FunctionalityX lives within the class dealing with FunctionalityX.
I'd leverage your web.config. I'm sure you're already doing this, but just make sure that you're not duplicating configuration efforts. The Web.Config is the right place for most of it and you can add more. Classes already exist for pulling configuration information out of the web config.
Alright, with that having been said, barring those two paths:
I'd set your class to static so you can just reference your class from anywhere without instantiation like this: ApplicationSettings.SettingValue.
I'd have explicit settings properties on your ApplicationSettings class and reference them directly that way. If they aren't instantiated, you can lazy load them from the XML as they are needed.
I'd cache your settings if they aren't dynamic.
So there's some general tips that might yield a better solution. It's hard to recommend something concrete without further information on how it'll be used.
FINAL EDIT:
After some discussion in the comments below, we found that this resource here fixed the OP's issue:
http://haacked.com/archive/2007/03/12/custom-configuration-sections-in-3-easy-steps.aspx
I would say no. There likely is a better way to do what you are attempting to do.

Change model after database is created on EF4 code only

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.

Resources