简体   繁体   中英

Linq how to Extend\Override existing toList() Method

I am using Linq to Sql. I would like to open the transaction scope when I call (System.Linq) toList() method. Therefore, I was trying to override default toList() method by creating custom extension class and thereby creating new version of toList(). But within the custom toList() extension, I would like to call existing default (system.linq) ToList() method. But I am not able to do that. Please see the example below:

Code:

public static int GetRecordsWithNoChangeToQuery()
{
    string connection = ConfigurationManager.ConnectionStrings["EventConn"].ConnectionString;
    using (var ctx = new EventsDataContext(connection))
    {
        var records = (from m in ctx.Event select m).ToList(); //calling custom extension method
        return records.Count();
    }
}

LinqExtenionHeler

public static class LinqExtension
{
    public static TransactionScope CreateLockTransaction()
    {
        var options = new TransactionOptions
        {
            IsolationLevel = IsolationLevel.ReadCommitted
        };
        return new TransactionScope(TransactionScopeOption.Required, options);
    }

    //custom extension method
    public static List<T> ToList<T>(this IEnumerable<T> query)
    {
        using (TransactionScope ts = CreateLockTransaction())
        {
            return query.ToList(); //fails, not able to call system.linq .toList method
        }
    }
}

In the above code when I call query.ToList(), itsthrows error. As, it is trying to call itself.So how to call default (syste.linq) query.toList() from the same name custom extension method?

An extension method is just a fancy way to call a public static method. You can still call it the normal way and sometimes you have to.

 return System.Linq.Enumerable.ToList(query); 

However, I do support the comments that scream "wait, why are you doing this?". It seems like a suboptimal way to go about this. Maybe you should ask a more open question about your problem to get a better answer for your global problem, this is just fixing your local syntactical problem.

An extension method that you create for List , it will call internally to itself because type of query is IEnumerable and this will through exception or may be in deadlock condition. so for ToList Extension method you can do one thing that passing parameter can be IQueryable. So synatax as-

public static List<T> ToList<T>(this IQueryable<T> query)
{ using (TransactionScope ts = CreateNoLockTransaction()) { return query.AsEnumerable().ToList(); } }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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