Entity Framework concurrency with datetime field

c# concurrency entity-framework-core

Question

I have an issue when I update an entity of my model:

var intervenant = this.IntervenantRepository.GetAll().FirstOrDefault(intervenant => intervenant.Id == intervenantId);

 if (IsInscrire)
 {
     intervenant.MotifdesinscId = null;
     intervenant.IsInscrit = true;
 }

this.IntervenantRepository.Update(intervenant);

I handle concurency with the property LastModificationTime in the intervenant entity model:

[ConcurrencyCheck] 
public DateTime LastModificationTime { get; set; }

When I update my entity with the source code above I get a DbUpdateConcurrencyException, and I think the problem is that the data in that I get in my property LastModificationTime is 2020-03-09T10:02:37, but in the database the column contains the data 2020-03-09 10:02:37.4570000.

Is there any solution that can let me handle this problem because I get it also in other entity ?

1
1
3/9/2020 10:51:09 AM

Popular Answer

My suggestion would be to ignore the LastModificationTime property altogether and use the TimestampAttribute. This is effectively what @marc_s suggests in his comment.

public class Intervenant
{
    // Your properties here

    [Timestamp]
    public byte[] RowVersion { get; set; }
}

TimeStamp-dataannotations-attribute-in-code-first.

It uses a byte array that represents the timestamp in order to avoid such issues as the one you have.

It can only be applied once in an entity class to a byte array type property. It creates a column with timestamp data type in the SQL Server database. Entity Framework API automatically uses this Timestamp column in concurrency check on the UPDATE statement in the database.

If you don't want to use multiple values and let the framework handle it on it's own use this. It will extend the table a bit but it will solve any such issues.

ConcurrencyCheckAttribute

1
3/9/2020 11:40:07 AM


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