避免覆盖数据库中的内容 [英] Avoid overwriting content in database

查看:78
本文介绍了避免覆盖数据库中的内容的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,

我有以下用例

我的数据库表

CREATE TABLE [shiftreport].[Records]( [Id] [bigint] IDENTITY(1,1) NOT NULL, [EntryText] [varchar](max) NULL, [Created] [datetime] NULL, [Updated] [datetime] NULL, CONSTRAINT [PK_Records] PRIMARY KEY CLUSTERED ( [Id] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

使用实体框架,我现在获取记录并将其呈现给用户表单。从该表单,用户可以修改EntryText的内容。如果他/她希望安全,则从该表单创建一个新对象,填充从表单派生的
Id和EntryText的属性。

Using the Entity Framework, I now get a record and present it to the user into a form. From that form, the user can modify the content of the EntryText. If he/she wishes to safe, then a new object is created from that form, populating the properties for Id and EntryText derived from the form.

然后以下c#是正在使用

Then the following c# is being used

public static void SetSingleToDatabase(Record record)
        {
            record.Updated = DateTime.UtcNow;
            
            var context = new DbContext("MyEntities");
            var db = context.Set<Record>();
            db.AddOrUpdate(record);
            context.SaveChanges();
        }

我确保将当前时间戳写入数据库,但执行此操作时,新数据正在编写,但Created列为NULL。我理解为什么它是NULL,正在编写的对象Record没有这个属性
set。但它仍然不应该消除现有的内容。

I make sure that the current timestamp is being written to the database, but when this is executed, the new data is being written, but the column Created is NULL. I understand why it is NULL, the object Record which is being written does not have this property set. But it should still not wipe out the existing content.

有没有办法告诉EF"只覆盖非空的列"?

Is there a way to tell EF to "only overwrite columns which are not null"?

推荐答案

https://forums.asp.net/t/2107047.aspx?How+to+update+single+field+with + EF

现在,您可以遍历字段以查看设置.IsModified属性是否为NULL。

Now you could loop over the fields to see whether it's NULL to set the .IsModified property.


这篇关于避免覆盖数据库中的内容的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆