What is the best pattern to use LINQ to C#

public class CommonService
{
    private readonly DataContext _context;

    public CommonRepository()
    {
        _context = new DataContext();
    }

    public CommonRepository(DataContext context)
    {
        _context = context;
    }

    public List GetAll()
    {
        var query = from m in _context.MyModel
                    select m;
        return m.ToList();
    }
}

or


    public class CommonService
    {
        public List GetAll()
        {
            using (DataContext context = new DataContext())
            {
                var query = from m in context.MyModel
                            select m;
                return m.ToList();
            }
        }
    }

or you have more pattern, suggest me please.


There is one major difference here: The first code sample keeps a single DataContext for the lifetime of the service, while the second example spins up a new one for each operation. The second example is usually correct because with Change Tracking, DataContext can get huge and you can accidentially commit stuff you didn't mean to commit if something else calls SubmitChanges() .

See Multiple/single instance of Linq to SQL DataContext


You can use both patterns, but always make sure that the context will have a short lifespan. The first option allows you to create methods in CommonService that need a context, but without having to create one in each and every method. So it prevents repetitive code. Also, it allows IoC containers to inject a context into CommonService by constructor injection.

If you go for the first option (which I'd lean to doing), you may consider making CommonService implement IDisposable , giving it a Dispose method in which the context is disposed. This will also encourage you to use the CommonService in a using construct and thus limit its lifespan.

链接地址: http://www.djcxy.com/p/53762.html

上一篇: foreach语句不能对'object'类型的变量进行操作

下一篇: 什么是使用LINQ to C#的最佳模式