简体   繁体   English

实体框架仅保存一些字段

[英]Entity Framework only saves some fields

I have a GridView that pulls data using Entity Framework. 我有一个使用实体框架提取数据的GridView。 The RowUpdating event is giving me a weird problem. RowUpdating事件给我一个奇怪的问题。 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: 在方法中,我从GridView中获得给定datakey的项目:

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. 在调试时,在context.SaveChanges()之后,我看到Field1和Field2保存了它们的新值,而ModifiedDate变回了以前的值。

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. 我唯一认为会导致这种情况的是,当我查看.edmx文件中的表时,ModifiedDate字段在StoreGeneratedPattern中具有“ Computed”。 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. 例如,用户插入没有ModifiedDate的项目,SQL Server在创建时将getdate()放入字段中。

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. 问题确实出在正在计算的StoreGeneratedPattern中。 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. 问题在于默认约束仅在未提供任何内容的情况下才会触发,但是为UPDATE命令生成的查询EF发送类似ModifiedDate = NULL的信息。 So EF says i'll send ModifiedDate = NULL, but it will be overridden once the DB runs this update query. 因此,EF表示我将发送ModifiedDate = NULL,但是一旦数据库运行此更新查询,它将被覆盖。 Then the DB says ok I will supply a calculated value for ModifiedDate if the user did not supply one. 然后,数据库说好,如果用户不提供,我将为ModifiedDate提供一个计算值。 Oh wait, I see they supplied a ModifiedDate I don't need to run my constraint. 哦,等等,我看到他们提供了ModifiedDate,我不需要运行约束。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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