尝试为 IDbSet 创建添加扩展方法

本文关键字:添加 扩展 方法 创建 IDbSet | 更新日期: 2023-09-27 18:30:29

我正在尝试为我的DBContext(db)和IDbSets之一创建一个扩展方法。我希望能够像这样调用扩展:

db.UploadedFile.AddFile
(
    SessionUser.ProfileId,
    model.UploadingFile.FileName,
    serverPath,
    model.ProjectSubmissionId
);

这似乎有效,但我想稍后再说,在一个数据库之后。SaveChanges(),获取添加值的主键 ID。

这是我到目前为止所拥有的:

public static class UploadedFileExtensions
{
    public static bool AddFile
    (
        this IDbSet<UploadedFile> files, 
        Guid uploadedByProfileId,
        string fileName,
        string filePath,
        Guid? associatedWithId
    )
    {
        var newFile = new UploadedFile
        {
            UploadedByProfileId = uploadedByProfileId,
            FileName = fileName,
            FilePath = filePath,
            FileExtension = Path.GetExtension(fileName),
            Submitted = DateTime.Now,
            Modified = DateTime.Now,
            IsActive = true
        };
        if (associatedWithId != null) newFile.AssociatedWithId = associatedWithId;
        return files.AddFile(newFile);
        //return true;
    }
    public static bool AddFile(this IDbSet<UploadedFile> files, UploadedFile file)
    {
        files.Add(file);
        return true;
    }
}

尝试为 IDbSet 创建添加扩展方法

根据数据库上下文代码的设置方式,您可以执行以下操作:

    private int GetMaxPrimaryKeyID()
    {
        return MyRepository.Items.Select(o => o.ID).DefaultIfEmpty().Max();
    }

其中项目是:

    IEnumerable<T> Items { get; }

假设这是一个身份ID,我认为在它提交到数据库之前,您无法获得它。

我会从上下文中包装或继承(工作单元模式对此有好处),并用您自己的方法覆盖 SaveChanges 方法。提交数据后,您可以看到分配了哪个 ID 值。

像这样:

public override void SaveChanges()
{
    UploadedFile[] newFiles = base.ChangeTracker.Entries<UploadedFile>()
                    .Where(x => x.State == EntityState.Added)
                    .Select(x => x.Entity)
                    .ToArray()
    base.SaveChanges();
    //id values should be available to you here in the newFiles array
}

编辑:经过反思,您实际上没有必要在这里覆盖任何内容。您可以直接将上述代码示例与上下文对象一起使用。您真正需要做的就是在提交后(但在释放上下文之前)使用 ChangeTracker 属性检查实体。