Update a data without modifying CreatedBy and CreatedDate while updating the existing record

.net-core c# dbcontext entity-framework-core

Question

As am updating the data which is already present in database and that table has the columns like CreatedBy, CreatedDate, ModifiedBy, ModifiedDate. CreatedBy and CreatedDate is inserted when the new row is created but while updating, I don't need to update CreatedBy and CreatedDate and I need to modify only ModifiedBy and ModifiedDate.

As shown in the below code, it will update the CreatedBy as null and CreatedDate as like 01/01/0001 something like this.

_Context.UserProfile.Update(userProfile);

and my model is like,

public class MyModelUserProfile
{
    public int Id { get; set; }
    public string Email { get; set; }
    public string Username { get; set; }
    public string FirstName { get; set; }
    public string CreatedBy { get; set; }
    public string ModifiedBy { get; set; }
}

Is there any way to avoid updating CreatedBy and CreatedDate column? I can do that by getting that particular record by its email id but i don't want to hit the database once again for this.

1
0
1/22/2019 9:17:50 AM

Accepted Answer

The EF Core intended way is to set AfterSaveBehavior property to value other than the default Save:

Gets a value indicating whether or not this property can be modified after the entity is saved to the database.

If Throw, then an exception will be thrown if a new value is assigned to this property after the entity exists in the database.

If Ignore, then any modification to the property value of an entity that already exists in the database will be ignored.

There is no dedicated fluent API yet, so you need to set it directly through mutable property metadata like this:

entity.Property(e => e.DateCreated)
    .HasDefaultValueSql("(getdate())")
    .Metadata.AfterSaveBehavior = PropertySaveBehavior.Throw; // <-- 

Update (EF Core 3.x): Starting with EF Core 3.0, many properties like this have been replaced with Get / Set extension method pairs, so the relevant code now is as follows:

    .Metadata.SetAfterSaveBehavior(PropertySaveBehavior.Throw); 
6
4/14/2020 4:04:21 PM

Popular Answer

[Required, DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public DateTime DateCreated {get; set;}


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow