【问题标题】:Check if an entry already exists in Entity Framework检查实体框架中是否已存在条目
【发布时间】:2020-08-15 06:46:22
【问题描述】:

好的,我知道这个问题在标题中听起来很愚蠢,但请听我说完。

我正在使用实体框架在 ASP.NET 中制作 API。问题是,它不支持自动生成 UUID 作为 Id 和创建自动 CreatedAtUpdatedAt 列。 我遵循了这个教程: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


    【解决方案1】:

    一种选择是像这样装饰您的 ID:

    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    [Key]
    

    然后您不必担心它是独一无二的。 Db 将在插入时处理它。我认为当你这样做时它在 sql 中使用 newsequential Id 命令而不是 newid。

    您可以确认运行新迁移后转到sql并检查id列的默认值,如果是newid,请确保将其更改为newsequentialid,您会没事的。

    【讨论】:

    • 谢谢,但这是否支持 UUID?而且我仍然需要在SaveChanges() 方法中留下关于创建 UUID 的行,对吗?
    • 不,你不需要覆盖它。就在您调用 dbcontext 上的 Add 之前,设置 created by 等字段,或者您甚至可以设置 created by 等的默认值。在您的基本实体中,或者最好将其设置为 [DatabaseGenerated(DatabaseGeneratedOption.Computed)]。这将花费插入的日期时间
    • 成功了吗?请不要忘记将其标记为答案?
    • 对不起,今天是周末,周一和周二有国定假日。一旦我尝试过,我不会忘记标记它;)我会看看今天是否有时间,但请耐心等待。知道我无论如何都很感激:p
    猜你喜欢
    • 1970-01-01
    • 2014-08-08
    • 2011-08-31
    • 1970-01-01
    • 2011-08-26
    • 2021-01-07
    • 2015-01-07
    • 2014-07-02
    • 1970-01-01
    相关资源
    最近更新 更多