从使用PHP开始,它非常直接地使用时间戳,但是使用实体框架( Entity ),这有点让人头疼。
发布于 2020-09-06 01:26:07
我确信您正在使用时间戳来处理一些并发冲突。在实体框架(核心)中,实际上有两种方法可以做到这一点
使用并发令牌将实体类中的特定属性/列标记为检查并发conflict.
设置属性的并发性检查
可以使用实体类上的数据注释配置并发令牌。
public class BookEntity
{
public int BookId {get; set;}
public string Title {get; set;}
// This tells EF that this property is a concurrency token,
// which means EF will check it hasn't changed when you update it
[ConcurrencyCheck]
public DateTime PublishedOn {get; set;}
// Other properties follow...
}还可以使用fluent API配置并发性检查。
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<BookEntity>()
.Property(p=> p.PublishedOn)
.IsConcurrencyToken();
// ...other configurations follow...
}在属性上设置时间戳
您可以使用实体类上的数据注释配置时间戳。
public class BookEntity
{
public int BookId {get; set;}
public string Title {get; set;}
// This tells EF to mark ChangeCheck property as a timestamp,
// This causes EF to check this when updating to see if this has changed
[Timestamp]
public byte[] ChangeCheck {get; set;}
// Other properties follow...
}使用Fluent API配置时间戳
protected override void OnModelCreating(ModelBuilder builder)
{
// Value of ChangeCheck will be changed each time the row
// created/updated
builder.Entity<BookEntity>()
.Property(p=> p.ChangeCheck)
.IsRowVersion;
// ...other configurations follow...
}这两种配置都在表中创建一个列,每当对该表进行插入或更新时,数据库服务器将自动更改该列。
设置计算机/用户友好的TimeStamp
这只能通过Fluent API来完成。
public class BookEntity
{
public int BookId {get; set;}
public string Title {get; set;}
// Column you set up as computed
// You give it a private setter, as its a read-only property
public DateTime DateModified {get; private set;}
// Other properties follow...
}然后通过Fluent API配置列。
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<BookEntity>()
.Property(p=> p.DateModified)
.HasComputedColumnSql("getutcdate()")
.ValueGeneratedOnAddOrUpdate();
// ...other configurations follow...
}.HasComputedColumnSql("getutcdate()")将告诉EF为该列计算一个值;在本例中,为了获得当前的utc日期时间,.ValueGeneratedOnAddOrUpdate()将让EF知道该列是计算出来的,因此应该对所做的任何更新更新该列。
发布于 2020-09-05 23:52:45
这里有一个对我有用的解决方案。首先,我有一个基本实体,所有实体都继承它:
public abstract class DbEntity
{
[Column("created_at")]
public DateTime CreatedAt { get; set; } = DateTime.Now;
[Column("updated_at")]
public DateTime UpdatedAt { get; set; } = DateTime.Now;
}然后,我为UpdateMethod添加了一个扩展方法:
public static class DbSetExtension
{
public static EntityEntry<TEntity> UpdateCustom<TEntity>(this DbSet<TEntity> dbSet, TEntity dbEntity)
where TEntity : class
{
dbEntity.GetType().GetProperty("UpdatedAt")?.SetValue (dbEntity, DateTime.Now, null);
return dbSet.Update(dbEntity);
}
}这对我来说很好。我将感谢关于其他人如何处理这个场景的反馈。
P.S:即使在为列设置了默认的SQL之后,[DatabaseGenerated(DatabaseGeneratedOption.Computed)]方法也不适用于我。
https://stackoverflow.com/questions/63759516
复制相似问题