c# - DbContext corrupts attached entities: why? -
i've got code this:
activity[] getallactivities() { using (schedulecontext ctx = new schedulecontext()) return ctx.activities.asnotracking().toarray(); }
the aim have simple in-memory cache of data: activities
mapped db view summarizes need.
if omit asnotracking
returned objects non-deterministically corrupted: properties on returned objects aren't set correctly, , 1 object's property value duplicated in other objects' properties. there's no warning or exception; neither on ef4.3.1 nor ef5rc2. both clr 4 , 4.5 release candidate exhibit same behavior.
the activity
objects simple; consisting solely of non-virtual properties of basic type (int
, string
, etc.) , have no key nor relationship other entity.
is expected behavior? can find documentation this?
i understand change tracking cannot work once relevant dbcontext
gone, i'm surprised materialized properties corrupted without warning. i'm worried i'll forget asnotracking
somewhere in more complex scenario , plausible wrong results.
edit: entity looks follows. jonathan & kristof; there indeed column inferred id!
public class activity { public string activityhostkey { get; set; } public int activityduration { get; set; } public int activitylastedchanged { get; set; } public string activityid { get; set; }//!!! public string modulehostkey { get; set; } public string modulename { get; set; } ...
i think "frequently 1 object's property value duplicated in other objects' properties" , activity
objects "and have no key" key pieces of information here (no pun intended).
when importing view (which doesn't have primary key), ef guesses @ primary key is. if tracking enabled, uses primary key make sure single copy of each entity created in memory. means if load 2 rows same values field ef guessed pk, values second row overwrite first.
as data being "non-deterministically corrupted", that's because database doesn't guarantee order rows returned in, , it's "last-in-wins" process in ef, if order of records changes db, record gets keep it's values changes too.
try marking more columns part of primary key, or modifying view (or definingquery in edmx) contain column based on row_number function can use primary key.
Comments
Post a Comment