【发布时间】:2020-08-15 06:46:22
【问题描述】:
好的,我知道这个问题在标题中听起来很愚蠢,但请听我说完。
我正在使用实体框架在 ASP.NET 中制作 API。问题是,它不支持自动生成 UUID 作为 Id 和创建自动 CreatedAt 和 UpdatedAt 列。
我遵循了这个教程:https://www.entityframeworktutorial.net/faq/set-created-and-modified-date-in-efcore.aspx
为了解决这个问题,我创建了一个名为 BaseEntity 的基类,我在所有模型中都使用了它。它看起来像这样:
public class BaseEntity
{
public Guid Id { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
}
我所有的模型都只是简单地像这个例子那样实现它:public class User : BaseEntity {}。
现在我在实体框架上覆盖了SaveChanges() 方法,以允许处理我自己的代码,自动填充CreatedAt 并更新UpdatedAt 列。现在我也想自动生成一个 UUID,但众所周知,它们并不总是 100% 唯一的。由于这将是一个大型项目,因此我确实需要检查一下,即使机会很小。
我重写的SaveChanges() 方法如下所示:
public override int SaveChanges()
{
// Get the entries wether they were modified. This happens, so anything that wasn't changed, won't be updated in 'UpdatedAt'
var entries = ChangeTracker
.Entries()
.Where(e => e.Entity is BaseEntity && (
e.State == EntityState.Added
|| e.State == EntityState.Modified));
// Foreach over all database entries
foreach (var entityEntry in entries)
{
// UpdatedAt should always be updated, no matter what (if there is a change)
((BaseEntity) entityEntry.Entity).UpdatedAt = DateTime.Now;
// If the entry is new, also insert 'Id' and 'CreatedAt'
if (entityEntry.State == EntityState.Added)
{
((BaseEntity) entityEntry.Entity).CreatedAt = DateTime.Now;
((BaseEntity) entityEntry.Entity).Id = Guid.NewGuid();
// TODO: Here I want to automatically generate a UUID for a new model. But how?
}
}
// Now return to the base method
return base.SaveChanges();
}
现在我的问题是,如何检查 UUID 是否已经在数据库中,并在需要时生成不同的 UUID?在需要执行此操作的位置上有TODO 评论。我已经对必须在注释上方生成 UUID 的代码进行了一些预览。
希望任何人都可以帮助我。
【问题讨论】:
标签: asp.net entity-framework asp.net-core asp.net-web-api entity-framework-core