Avoid overwriting content in database

时间:2018-03-25 19:19:40

标签: c# sql-server entity-framework

I have the following use case

My database table

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)
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]

ALTER TABLE [shiftreport].[Records] 
    ADD CONSTRAINT [DF__Records__Created__2DB1C7EE]  
        DEFAULT (getutcdate()) FOR [Created]
GO

ALTER TABLE [shiftreport].[Records] 
    ADD CONSTRAINT [DF__Records__Updated__2EA5EC27]  
        DEFAULT (getutcdate()) FOR [Updated]
GO

Using 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 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.

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();
}

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.

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

1 个答案:

答案 0 :(得分:0)

As per my understanding it looks different as it should be. what you need to do is

public static void SetSingleToDatabase(Record record)
        {
            record.Updated = DateTime.UtcNow;

            var context = new DbContext("MyEntities");
            var recordById = context.GetById(x=>x.record.Id)
            //now manualy you must assign recordById = record
            var db = context.Set<recordById >();
            db.AddOrUpdate(recordById );
            context.SaveChanges();
        }

The purpose is that getting RecordById to map your record with entity instance. Now when you try to update it map with object if data is not exist against this ID then it will new entry otherwise it will update it.