Entity Framework create update query unnecessary
I am trying to update record with LINQ to SQL but in some case value is same as original value then also Enitty framework create Update query unnecessary.
var objForupdate = context.temp.FirstOrDefault();
if(objForupdate != null)
{
objForupdate.Name = "VJ"; // Original Value also "VJ"
}
// Create update query for above.
context.SaveChanges();
Updated Hey Steven Wood
Here I have scenario where my DB has 20 fields. Sometime some data is same as original data then also Entity framework create update query for that.
It is simple if data row is not in dirty state then no need to update it. But entity frame work create Update query for that also. Just use profile tool to check what kind of query executed on DB server after SaveChanges() method executed.
Solutions
Use following function to check entity object changed or not. If not then it will change it to EntityState.Unchanged from EntityState.Modified.
public static bool ChangeStateIfNotModified(this EntityObject entity, ObjectContext context)
{
if (entity.EntityState == EntityState.Modified)
{
ObjectStateEntry state = ontext.ObjectStateManager.GetObjectStateEntry(entity);
DbDataRecord orig = state.OriginalValues;
CurrentValueRecord curr = state.CurrentValues;
bool changed = false;
for (int i = 0; i < orig.FieldCount; ++i)
{
object origValue = orig.GetValue(i);
object curValue = curr.GetValue(i);
if (!origValue.Equals(curValue) && (!(origValue is byte[]) || !((byte[])origValue).SequenceEqual((byte[])curValue)))
{
changed = true;
break;
}
}
if (!changed)
{
state.ChangeState(EntityState.Unchanged);
}
return !changed;
}
return false;
}
If you're looking to not execute the update if the two values are the same, why not do something like:
if(objForUpdate.Name != orignalValue){
context.SaveChanges();
}
Make sure you dispose your context where appropriate. For instance, if this is in a MVC controller, I'd dispose your context in the controller's Dispose()
method.
You should use String.Empty
instead of '' and verify that the value is really the same or not while debugging.
EDIT: Are you sure it's exactly the same value?
If I take a look at the generated code for a property, it looks like this:
[EdmScalarPropertyAttribute(EntityKeyProperty=true, IsNullable=false)]
[DataMemberAttribute()]
public global::System.String id
{
get
{
return _id;
}
set
{
if (_id != value)
{
OnidChanging(value);
ReportPropertyChanging("id");
_id = StructuralObject.SetValidValue(value, false);
ReportPropertyChanged("id");
OnidChanged();
}
}
}
private global::System.String _id;
So the value are being compared. Verify the code generated and set a breakpoint to debug it. If the state is changed, then a query would occur. If it's not entering inside the if condition and the update query still occur, the problem is elsewhere.
链接地址: http://www.djcxy.com/p/33580.html上一篇: 实体框架6.1更新记录的子集
下一篇: 实体框架创建更新查询不必要