简体   繁体   中英

Avoid passing around a context when making LINQ SQL OO?

Right now I'm making convenience classes that use LINQ.

Ex:

    public static bool Remove(Customer c,KezberPMDBDataContext context)
    {
        if (c != null && context != null)
        {
            KezberPMDBDataContext db = context;
            db.Customers.DeleteOnSubmit(c);
            db.SubmitChanges();
            return true;
        }

        return false;
    }

I have other functions like this:

public static Customer Get(string description,
            KezberPMDBDataContext context = null)
        {
            KezberPMDBDataContext db = GetContext(context);
            return (from p in db.Customers
                    where p.CustomerDescription == description
                    select p).FirstOrDefault();
        }

The problem is to do a task like removing a customer, I need the context.

Is there a way to do this without always needing to pass the context around?

Yes, create a new context for each of these operations.

Data contexts are not expensive to create. The rely on connection pools so that each new context doesn't have the overhead of creating new connections. Unless you have a compelling reason to back the operations that you're submitting, you probably are better off not passing around the contexts.

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