简体   繁体   中英

Entity Framework only saves some fields

I have a GridView that pulls data using Entity Framework. The RowUpdating event is giving me a weird problem. Pulling desired data, Inserting, and Deleting works just fine, it's just Updating.

In the method I get the item given the datakey from the GridView:

int dataKey = Convert.ToInt32(gridView.DataKeys[e.RowIndex].Value);
MyEntity ent = context.MyEntities.First(x => x.Key == dataKey;

Then I update the necessary fields and save:

ent.Field1 = "some data";
ent.Field2 = "other data";
ent.ModifiedDate = DateTime.Now;
context.SaveChanges();

While debugging, after context.SaveChanges() I see Field1 and Field2 saved their new values whereas ModifiedDate changed back to what it had before.

The only thing I could think that would cause this is when I look at the table in the .edmx file the ModifiedDate field has "Computed" in StoreGeneratedPattern. However, this is supposed to be just computed initially. For example, a user inserts an item without a ModifiedDate and SQL Server puts getdate() in the field on creation.

USE [MyDB]
GO

ALTER TABLE [dbo].[MyEntities] ADD  CONSTRAINT
DF_MyEntities_ModifiedDate]  DEFAULT (getdate()) FOR [ModifiedDate]
GO

the problem was indeed in the StoreGeneratedPattern being computed. If it is set to Computed it overrides whatever the user sets the value as and tries to find the constraint in the DB that will give it it's computed value. The problem lies with a default constraint only fires if nothing is supplied, but the query EF generates for the UPDATE command sends something like ModifiedDate = NULL. So EF says i'll send ModifiedDate = NULL, but it will be overridden once the DB runs this update query. Then the DB says ok I will supply a calculated value for ModifiedDate if the user did not supply one. Oh wait, I see they supplied a ModifiedDate I don't need to run my constraint.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM