c#


How to transition partial update operation from ObjectContext to DbContext


I am using entity framework 5.0. I am in a rocess od changing my app from ObjectContext to DbContext model. DbContext should be according to microsoft the recommended approach. I use database forst approach and I have generated model form database.
But, at a very first simple task there is a problem. Namely simple update of a record is broken.
Let's have a simple table Item, for ilustration only:
Item
(
ItemId int NOT NULL, -- Primary key
Name nvarchar(50) NOT NULL,
Description NVARCHAR(50)
)
I have noticed that using DbContext does not support updating a record not as ObjectContext does.
In my application I have a simple update method.
public void UpdateItem()
{
MyContext context = new MyContext();
Item item = new Item();
item.ItemId = 666;
context.Items.Attach(item);
// From this point onward EF tracks the changes I make to Item
Item.Description = "Some description";
context.SaveChanges();
}
Using ObjectContext this method correctly updates a record. Using SQL profiler I can see that it generates something like this (greatly simplified!!!)
UPDATE Item
SET Description = 'Some description'
WHERE ItemId = 666
If, however I try to do the same thing in DbContext I get the exception:
System.Exception: Items.aspx.cs - logged from CustomError() ---> System.Data.Entity.Validation.DbEntityValidationException: Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.
at System.Data.Entity.Internal.InternalContext.SaveChanges()
at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
at System.Data.Entity.DbContext.SaveChanges()
And no database UPDATE is issued to Sql server.
I guess that DbContext validates all the properties and the property Name is null. This by design. I do not intend to modify it, I do not even know what is it and I do not need to know what is it.
Only the property Description was changed. Clearly ObjectContext does not track changes correctly.
How can this problem be resolved?
I have researched the issue and found the something on updating records.
For example this link: http://stackoverflow.com/a/15339512/4601078
db.Users.Attach(updatedUser);
var entry = db.Entry(updatedUser);
entry.Property(e => e.Email).IsModified = true;
// other changed properties
db.SaveChanges();
But this is horrible code. For every property on should add a line like:
entry.Property(e => e.Email).IsModified = true;
This produces ugly unreadable code, an I suspect lamda expression are not stelar in performance.
Even worse are those who propose to make a roundtrip to DB to fetch existing records with all properties populated, update it and the save changes. This is a no go with regard to performance.
So, how to tackle with simple entity updates or is this DbContext just another item in microsofts collection of dead ends which serve no real purpose?
DbContext doesn't really track changes by watching properties, it compares the values to previously known values. And validation always works on the entire entity so the only real choice if you want to do things this way is to disable validation during this operation. See Entity Framework validation with partial updates
If you know for sure that the changes you apply are valid, or you have custom code to validate them, you can turn off validation by EF altogether:
db.Configuration.ValidateOnSaveEnabled = false;
This works OK as long as you do it your way: attach a new entity with a known Id (aka a stub entity) and then modify its properties. EF will only update the properties it detects as having been modified (indeed by comparing original and current values, not, as ObjectContext did, by change notifications). You shouldn't mark the entity itself as modified.
If you don't want to turn off EF's validation, but neither want to mark individual properties as modified, I think this could be a useful alternative (brought to my attention by Alex's answer).

Related Links

Modify object without affecting base database table in Entity Framework?
How do I apply events to a dynamically created picturebox? [duplicate]
Use winformchart in a UserControl in WPF project
ASP.NET converting HTML to PDF
Unity 3D VR (Unity 5.6) How to add event trigger using c# script
To Convert Type Object to Char [duplicate]
For loop with 20 items skip each time
WPF Bind DependencyProperty to another DependencyProperty
Xamarin ListView not appearing
Requested value '1px' was not found. PDF Sharp. Is this a format error?
Jwt with new client
c# button 2 can only be click after button 1 clicked
Check open and close time in 3 different cases
c# - Cannot convert from List<DateTime?> to List<dynamic>
View is calling the wrong controller
Styling of scroll bar doesn't work

Categories

HOME
sql-server-2014
network-programming
pyspark
microcontroller
glsl
nagios
conceptual
opengl-es
atlassian-fisheye
symfony-3.2
cdn
ios-universal-links
jpql
decoding
mongodb-replica-set
logstash-configuration
opendaylight
legend-properties
summernote
jq
turn.js
ajaxcontroltoolkit
infinite-loop
sha
continuous-fourier
jms-topic
r-factor
folder
jboss-arquillian
rtos
android-scrollview
offset
apache-falcon
javafxports
kofax
web-technologies
python-venv
ocamlbuild
multivalue
appcmd
dotnet-cli
vertex
ajv
richtext
fckeditor
cedar-bdd
jira-agile
hfp
mod
dynamics-nav-2013
controlpanel
newlib
play-json
jts
transport
tess4j
textblob
android-networking
page-refresh
data-representation
gcc-warning
httpmodule
breeze-sharp
oxygenxml
parallel-port
disabled-control
sendy
connections
acrofields
mixradio
data-layers
imaplib
netbeans-plugins
mysql-error-1146
maven-javadoc-plugin
google-mirror-api
misfire-instruction
pechkin
forward-declaration
mandelbrot
kademlia
dd4t
uikit-dynamics
rbm
volatility
configurationsection
xcode4.6.3
shapado
google-email-audit-api
animationdrawable
nsundomanager
jquery-click-event
nyromodal
webdb
dojox.gfx
morfik
file-storage
memory-consumption

Resources

Encrypt Message