在C#中,是否存在将DBSet传递给方法的通用方法?

我目前有以下工作代码:

        private Converter RemoveAll<T>(List<T> databaseSet) {
             databaseSet
                .ForEach(item =>  this.myContext.Remove(item));
            return this;
        }

我可以像这样调用:

this.RemoveAll(this.myContext.Widgets.ToList());
this.RemoveAll(this.myContext.WhositsWhatsits.ToList());
// etc.

Where this.myContext is an instance of MyContext which extends DbContext; and Widgets, WhositsWhatsits, etc. are all instances of DbSet.

Because I always need to change the DbSet to a List, I'd rather just pass the DbSet as a parameter, like:

this.RemoveAll(this.myContext.Widgets);
this.RemoveAll(this.myContext.WhositsWhatsits);
// etc.

但是,如果我将方法更改为:

        private Converter RemoveAll<T>(DbSet<T> databaseSet) {
             databaseSet.ToList()
                .ForEach(item =>  this.myContext.Remove(item));
            return this;
        }

编译器抱怨“类型'T'必须是引用类型,才能在通用类型或方法'DbSet'中用作参数'TEntity'。

是否可以修改此方法,以便在调用它之前无需调用ToList()?

评论
  • 24K天然
    24K天然 回复

    The DbSet is restricted to have reference types as generic parameters. Therefore, you need to restrict your method to also work only for reference types. It can be acheved by using where clause as below.

    private Converter RemoveAll<TEntity>(DbSet<TEntity> databaseSet) where TEntity : class