尝试为IDbSet创建Add扩展方法

时间:2016-01-14 16:58:39

标签: c# entity-framework extension-methods

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

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

这似乎有效,但我想稍后在db.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;
    }
}

2 个答案:

答案 0 :(得分:0)

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

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

物品在哪里:

    IEnumerable<T> Items { get; }

答案 1 :(得分:0)

假设这是一个身份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属性在提交后检查您的实体(但在您处置上下文之前)。

相关问题