EF4 does not commit Updates - entity-framework-4

Sorry to ask such a general question: what can cause EF to insert records but not update ?
I face a strange situation where i change an entity and when i call SaveChanges(), the changes are not committed in the DB.
thanks
Jon

Are you keeping the ObjectContext alive for the entire lifetime of your entities? If not, when you re-attach the entities to a new ObjectContext for saving, the changes made may not be reflected and the entities may not be considered dirty.

Do you have a primary key defined?

Related

Model compatibility error

Setup
I have an app that uses ASP.NET Identity 2.0. The identity part shares a database with the rest of the tables needed by the application. So in one class library, I have a dbcontext that accesses the database for business data, and in another class library, I have the IdentityModel.cs, ie, the ApplicationDBContext.
Problem:
All worked fine, until I got in a muddle, trying to figure out how to work with migrations with the business data context. I ended up deleting the __MigrationHistory table and hence all the model metadata in the database for both the context.
I now get the following error:
Model compatibility cannot be checked because the database does not contain model metadata. Model compatibility can only be checked for databases created using Code First or Code First Migrations.
I deleted all migrations related to the business data, and re enabled migrations for that project. That had the effect of recreating the model metadata for the business dbcontext.
However, I can't figure out how to achieve the same for the Identity metadata.
Question:
How do I recreate the model metadata in __MigrationHistory for ASP.NET Identity 2.0?
Write below code in Global.asax.cs and try again...
Database.SetInitializer(new DropCreateDatabaseIfModelChanges<TsContext>());
I had to recreate the database and start again. I am still in the dark to the extent that I don't know if Neel's answer is the correct one for a production database. Right now, I don't have the time to properly research AspNet.Identity to find the solution to the problem. Sorry.
Prevention before Cure:
What I DO know is that the problem would not happen if I hadn't deleted the __MigrationHistory table. So the issue is one of self harming and so prevention rather than curing is the best option.
Therefore, the moral of the story is:
Moral:
Never, EVER, delete the __MigrationHistory table. Learn a bit more about it BEFORE doing any thing quite so silly, feckless, carless and downright dumb.

Having issues with deleting object graphs

I'm experiencing issues deleting parent objects in an object graph using breeze, when there are complex graphs of children involved. Every time I try to delete a parent, I get foreign key conflicts, even if there is only one simple child. Any advice? Before I post code here, I'd like to understand existing issues I should be aware of. My breeze controller is working with EF6.
The reason you are getting the error is because you have a foreign key constraint. In your code-first DBContext you establish a relationship between a parent and a child and you probably aren't telling EF what to do in case of deletion.
You can either enable the cascading deletes, or set the rules however you want using Fluent API. Check this answer for more details -
Cascade Delete Rule in EF 4.1 Code First when using Shared Primary Key Association

EntityState.Detached, do I need to reload?

All,
Using .Net 4 and EF 4.4 Database First.
Let's say I have a DbContext. I load data from this DbContext, do stuff, and then detach everything from the DbContext and dispose of the DbContext.
Then, I create a new DbContext (same model) and load other data that overlaps with data from the first DbContext. Do I need to, prior to executing my query, do Entry().Reload() or will the Detatched Entities refresh automatically when they're loaded into the new context.
The reason I ask is because I ran into an issue in the past with, when using the same DbContext, I had to manually reattach entities that were in a detached state and call Reload. So I'm wondering if in this situation the entities that were in a detached state from the prior DbContext are simply attached to the new DbContext or if they're also refreshed?
Yes, I know I could setup a simple test, but was curious to know if someone else out there has already done this so that they could share their findings with the SO Universe and save others wondering about this some time.
Hopefully this question makes sense.
Thanks.
Entities are not automatically attached to the new context. You must attach them manually. If you then just load overlapping data your entities will not be updated. You must force such update either by calling Reload or by using ObjectContext and MergeOption for the query. If you don't attach your detached entities and you just run the query on the new context you will get new data but you will have two instances of overlapped entities - one detached with old data and one attached with new data.
will the Detatched Entities refresh automatically when they're loaded into the new context?
No, they won't. Which is good, because you can attach changed entities (which often happens in a disconnected n-tier application). An automatic refresh would erase the changes. So you'll have to reload manually if you want a refresh.

Database cache that I'm not aware of?

I'm using asp.net mvc, linq2sql, iis7 and sqlserver express 2008.
I get these intermittent server errors, primary key conflicts on insertion. I'm using a different setup on my development computer so I can't debug. After a while they go away. Restarting iis helps. I'm getting the feeling there is cache somewhere that I'm not aware of. Can somebody help me sort out these errors?
Cannot insert duplicate key row in object 'dbo.EnquiryType' with unique index 'IX_EnquiryType'.
Edits regarding Venemos answer
Is it possible that another application is also accessing the same database simultaneously?
Yes there is, but not this particular table and no inserts or updates. There is one other table with which I experience the same problem but it has to do with a different part of the model.
How often an in what context do you create a new DataContext instance?
Only once, using the singleton pattern.
Are the primary keys generated by the database or by the application?
Database.
Which version of ASP.NET MVC and which version of .NET are you using?
RC2 and 3.5.
Two guesses for you:
1) If you've got a singleton DataContext, wouldn't that mean it's shared by all threads?
The MSDN reference for DataContext says an instance is "designed to last for one unit of work" and typically created "at method scope or as a member of short-lived classes".
I'd try moving away from the singleton pattern and creating a new context each time it is needed.
2) When you say your keys are generated by the database, is that through Identity fields, or some kind of "select max + 1" pattern? If not by an identity, then you may have concurrent connections obtaining the same "next" key value. Check your transaction isolation levels.
EDIT - following on from comment
Are you sure that the index violation is on the primary key? Using SQL Server Management Studio, primary keys are normally given a PK_ prefix, and IX_ is used for further indexes. Check the fields which go to make up "IX_EnquiryType" and ensure it's not just a rare logic problem that's causing your problems.
Well, it can be because of many reasons. I'll give you some questions. Please edit your question with the info about these, and it will be much more straightforward for us to help you.
Is it possible that another application is also accessing the same database simultaneously?
This would be the most likely reason. I experienced this, too.
How often an in what context do you create a new DataContext instance?
The best way would be to create a new one per request.
Are the primary keys generated by the database or by the application?
Which version of ASP.NET MVC and which version of .NET are you using?

How to prevent dirty write for web forums?

As a apprentice for web development, I have no clue of preventing dirty write for web forums. Is there any food for thought? Thanks in advance!
I'm working on ASP.NET MVC and Entity Framework.
Okay, sorry for misleading. The dirty write here means overwrite changes of another person in the database. While using a Optimistic Concurrency.
To do optimistic concurrency in the EF, you:
Add or select a field to use for optimistic concurrency control. We use a TIMESTAMP.
In the EF designer, change the ConcurrencyMode to Fixed for this property.
Serialize the "old" value of the field to a hidden field on the form.
Deserialize the "old" value when the form is submitted, and add it to the entity you're updating.
The EF will throw OptimisticConcurrencyException when the stored value doesn't match the old value during an update.

Resources