【问题标题】:Trying to create an Add extension method for an IDbSet尝试为 IDbSet 创建 Add 扩展方法
【发布时间】:2016-04-20 02:51:12
【问题描述】:

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

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;
    }
}

【问题讨论】:

  • 您的数据库上下文在哪里?您是否在使用存储库和工作单元模式?
  • 当我们开始这个项目时,我们被告知我们不需要存储库模式。我不同意,但这就是我们要走的路。我仍然认为我们可以开始使用存储库模式。有哪些有当前示例的好网站?
  • 值得一提的是,如果您实现存储库/工作单元,则不需要扩展方法,它可以成为存储库的一部分(最好以通用形式)。使用模式也有缺点,尽管它们可能会限制某些事情,所以你不应该急于做出改变

标签: c# entity-framework extension-methods


【解决方案1】:

假设这是一个身份 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 属性检查您的实体。

【讨论】:

    【解决方案2】:

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

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

    项目在哪里:

        IEnumerable<T> Items { get; }
    

    【讨论】:

      猜你喜欢
      • 2013-02-15
      • 1970-01-01
      • 2013-12-23
      • 2011-06-26
      • 2016-09-02
      • 1970-01-01
      • 2013-10-04
      • 2019-05-06
      • 2013-04-23
      相关资源
      最近更新 更多