简体   繁体   English

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

[英]In C#, is there a generic way to pass a DBSet to a method?

I currently have the following working code:我目前有以下工作代码:

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

which I can invoke like:我可以像这样调用:

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

Where this.myContext is an instance of MyContext which extends DbContext ; this.myContextMyContext的一个实例,它扩展DbContext and Widgets , WhositsWhatsits , etc. are all instances of DbSet .WidgetsWhositsWhatsits等都是DbSet的实例。

Because I always need to change the DbSet to a List , I'd rather just pass the DbSet as a parameter, like:因为我总是需要将DbSet更改为List ,所以我宁愿将DbSet作为参数传递,例如:

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

But if I change the method to:但是,如果我将方法更改为:

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

The compiler complains "The type 'T' must be a reference type in order to use it as a parameter 'TEntity' in the generic type or method 'DbSet'.编译器抱怨“类型'T'必须是引用类型才能将其用作泛型类型或方法'DbSet'中的参数'TEntity'。

Is it possible to modify this method so I can remove the need to invoke ToList() before calling it?是否可以修改此方法,以便在调用 ToList() 之前无需调用它?

The DbSet is restricted to have reference types as generic parameters. DbSet 仅限于将引用类型作为泛型参数。 Therefore, you need to restrict your method to also work only for reference types.因此,您需要限制您的方法也仅适用于引用类型。 It can be acheved by using where clause as below.它可以通过使用下面的where子句来实现。

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

Instead of using remove method, use removerange where you can avoid Call to ToList().代替使用 remove 方法,使用 removerange 可以避免调用 ToList()。 I have provided an extension method that will reduce code even more.我提供了一种扩展方法,可以进一步减少代码。

public static class DbContextExtension
{
    public static void RemoveAll<Tinput>(this DbSet<Tinput> dbset) where Tinput : class
    {
        dbset.RemoveRange(dbset);
    }
}

usage will be like.用法会像。

 this.myContext.Widgets.RemoveAll();

if u dont need extension method, just use如果您不需要扩展方法,只需使用

dbset.RemoveRange(dbset); dbset.RemoveRange(dbset);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM