ASP.Net Insert to database not updating - asp.net

I'm working with MSSQL Server 2008 and made a database in it.
Now i made a ASP.Net (MVC 4) project and connected it to the database. I let visual studio generate the Entity Data Model and everything is working fine so far.
Now i have a table for a many to many relation with ofcourse a PK, and two FK. When i manualy insert a row to the database with Microsoft SQL Server Management Studio and i refresh my web page this new row doesn't show up.
I'm 100% sure there is nothing wrong with the C# code (ASP.Net) but after X minutes the row show up :s.
Do i need to update the datasource somewhere or what do i do wrong? (it's my first ASP.Net project :))
Thnx!
Code edit:
private dbEntities db = new dbEntities();
This dbEntities is generated by visual studio from the SQL Server and contains models for all tables.

It sounds like your data context is stale (it's retrieving the data from memory and not going to the DB).
See this question or this one for a possible solution.
Edit: Looking at your sample code, I'm going to guess that this has been declared as a page (or class) member. You should wrap this in a using statement so the object context can be disposed:
e.g.
using (var db = new dbEntities())
{
//perform work
}

Related

How to properly update SQL database in Azure after EF Code First model of asp.net mvc model change?

It seems like I always have a variety of problems doing this, and usually I end up nuking the db out of frustration and rebuilding, but obviously there has to be some way to do this.
I have an existing asp.net mvc web app living with its sql db in azure. Works fine has some data that can be replaced but, again, the point is to learn how to update model without destroying the database.
In VS2017 I add one property public string ScreenShot { get; set; }
I make some small changes to my mvc and web api controllers to handle this extra property. I update my localdb via packmanager console and add-migration addprop and update-database. Works fine, run it locally, no probs.
Goto publish, goto settings, check update database. Click publish.
It hangs for like 5 or 6 min and I get:
Warning : A project which specifies SQL Server 2016 as the target platform may experience compatibility issues with Microsoft Azure SQL Database v12. when publishing
I try publishing several times and get the same thing. Google, look around, scratch my head, try again and it seems to publish. Site opens, and somehow I have lost my bootstrap theme. In fact in my Content folder I now have 4 files i believe are new: bootstrap-theme. (css,css.map, min.css, min.css.map) (same prefix , different suffix) as well as what I think are virgin versions of those without theme in the name, and seems to be the default mvc theme of black and white.
When I goto my app and I get an generic error and checking elmah I get:
System.InvalidOperationException: The model backing the 'TaskTrackerContext'
context has changed since the database was created. Consider using Code
First Migrations to update the database (http://go.microsoft.com/fwlink/?
LinkId=238269).
Well I really thought thats what I did. Almost forgot one thing! Maybe this is where my problem lies: I actually had to run two migrations-in addition to the model change I dropped a column that had never been used (scaffolding a controller for a DTO version of one of my models added it to my context which created a table).
I did create a new branch before making any of these change so I could just revert back but at some point I have to make this work and have to understand how to do it without destroying my db and remaking fresh.
A check in SQL object explorer shows it added the ScreenShot column to my table but didn't remove the unused table.
This works for me :
In visual Studio, go to publish settings and then select the option
Execute Code First Migration
Please see the screenshots below
Kind regards

How do i update an existing database to support ASP.NET Identity 2.0

I have a web solution that I upgraded to ASP.NET Identity 2.0. The problem i now face it that i have some solutions of this software running in production at several customers. When I try installing the new software (with ASP.NET Identity 2.0) on the existing database (full of their data). I then get an error: "The model backing the "ApplicationDbContext" context has changed singe the database was created"
How do i update the database in the existing solution to a database that fits the new ASP.NET Identity? I looked at the ASPnetUsers table and there has been added several new columns.
Is there a way to disable this check? Or is there a way to fix it?
Personally, I would create a new project/database containing just the ASP.Net Identity 2.0 features and create a dummy user (just to make sure that it all works correctly).
Then, use schema comparison between the new database and your existing database. You can then generate scripts to create the user tables in your customers' database.
You may still have further integration work to do, but it should get you over the hump.
I suppose you don't use EF code first. You could run your project in dev using code first and get the full DB structure including the Identity tables, then compare against the prod schema and implement the differences.
This should give you the hint:
http://blogs.msdn.com/b/webdev/archive/2013/12/20/updating-asp-net-applications-from-asp-net-identity-1-0-to-2-0-0-alpha1.aspx

Asp.Net Mvc 4 and Entity framework 5 code first database migration

I created an internet asp.net Mvc 4 application. It used EF5 code first, LocalDB by default. I have the following issues. I put all my tables in data context class MyContext and enabled database migration on it.
UsersContext. I added a field email in the table UserProfile. However, I cannot enable database migration on the default UsersContext since I already enabled migration on MyContext. I had to delete the database and let it recreate UserProfile table (I had to open the user register page first, otherwise it will create UserProfile without field email.)
I published the project to a server with IIS/Sql Server and keep working on the project. However, from time to time it shows the model of UsersContext were changed (not true) and I had to delete the database on the live server and let it recreate the database.
Sometimes it create the same index twice on a table in MyContext and it failed the migration. And I had to delete the database again for recreating.
How to prevent the above issues? Should database migration be disabled after go live? How to apply the Model/DB changes?

LinqToSQl changing Datasource

I am working on a web application project where the DAL is generated using LinqToSql designer in Visual Studio. All data access logic is in a separate project.
I created a copy of the database with same structure and same names for tables, views etc. I tried to change the connection string to the new source, but it is not working. Somehow, it still accesses the old database.
All of the following changes failed:
Changed the connection string in config files for all the projects in the solution which is now pointing to new data source.
Create a partial class for the DataContext and passed new connection string to the constructor after changing the connection string to "none" in Visual Studio LinqToSql designer properties.
Passed the connection string explicitly whenever I instantiated the DataContext.
Deleted the contents of bin and obj folders for the LinqToSql project and rebuilt everything.
My project is saving new data to the new datasource, but when reading data it is getting it from the old database, and also throwing null exceptions when it connects to the old DB for data.
What am I doing wrong? Is there any fix for this? What is the best way to make a project with LinqToSql DataContext point to a new datasource with the same data (for example: dev, staging, release, etc.)? Thanks.
If you are reading data from the old database, there must be a connect string or similar in your project that hasn't been updated.
There are three places where the LINQ to SQL designer might be storing the old connection information:
In the app.config file.
In the Settings.settings file.
In the default constructor for the DataContext.
Check all of them.
You could also use 'Find' to search your entire solution for any other references to the old database hard-coded into your application.

EF 4.1 Code First and Existing Database and .NET Membership

I have a database called ApplicationName_Development running on SQL Server 2008 R2 Developer edition on my development box.
I added .NET membership tables to the database with no problem. When I tried to get Code First working I received the following error message:
The server encountered an error
processing the request. The exception
message is "Model compatibility cannot
be checked because the database does
not contain model metadata. Ensure
that IncludeMetadataConvention has
been added to the DbModelBuilder
conventions.
After some googling, I discovered that I had to delete the database and let EF create the database. That's fine but I lost all my .NET membership tables. I can go back in and add the membership tables again but if my model changes and EF needs to recreate the database then I have to add the membership tables in again.
How do I get around this?
This is how code-first work. Main idea of code first is that you do not touch your database because it is responsibility of the model to create the database. If you want to customize your database you must create custom IDatabaseInitializer and add your custom SQL.
public class MyDbInitializer : DropCreateDatabaseIfModelChanges<MyContext>
{
protected override void Seed(MyContext context)
{
// Here run your custom SQL commands
context.Database.ExecuteSqlCommand("CREATE TABLE ....");
}
}
Now you only need setup your cutom intializer on the startup of your application:
Database.SetInitializer<MyContext>(new MyDbInitializer());
If you don't want to do it this way you must manually maintain your database and set initializer to null.
Found a easier workaround here. I hope this helps.
http://www.paragm.com/ef-v4-1-code-first-and-asp-net-membership-service/
Another option could be to use the System.Web.Management namespace. I've had great success with the code below:
string connectionString = ConfigurationManager.ConnectionStrings["MyDatabaseContext"].ConnectionString;
string database = "MyDatabaseName";
SqlServices.Install(database, SqlFeatures.All, connectionString);
It will just create the database and after that you can add users with the standard membership API.
Here's another possibility.
If you look at the MvcMusicStore sample - there's a SampleData class that is responsible for seeding the database on a rebuild. The SampleData class inherits from DropCreateDatabaseIfModelChanges, and overrides the Seed method. This class is passed to the Database.SetInitializer in the Application_Start method in global.asax.
I was getting the same error as you until I changed the parent class of SampleData to CreateDatabaseIfNotExist.
Then you can override the Seed method to insert any data you desire at startup, without it blowing away the database.
While you are developing, create 2 databases and two connection strings. One for SqlMembership (using aspnet_regsql) and one for your EF Application. If you would like to merge them into a single DB in production, just change the connection string in web.config.release to be the same. Then, EF model changes will just drop your apps db and not your membership DB.
By treating your authentication component separately, you will naturally decouple your authentication system from your application system. Then, if you wish to change membership providers, you will be better setup.
As the system grows, you will likely need to support non-pure models without EF code first, so this is a good template for going down that path.
I found the easiest way without playing with anything else was the following.
I ran the application first time with DropAndRecreatedatabase always in the Initilizer.
This created my database for the first time.
Following this I changed this to DropCreateDatabaseIfModelChanges.

Resources