Instantiating a context in LINQ to Entities

前端 未结 2 404
野性不改
野性不改 2020-11-29 06:17

I\'ve seen two different manners that programmers approach when creating an entity context in their code.

The first is like such, and you can find it all over the MS

2条回答
  •  爱一瞬间的悲伤
    2020-11-29 06:17

    The second option actually does not clean up after itself if that's what you mean. I prefer the using ObjectContext version every time because I don't have to dispose it after. Not sure I got the question right though... Too many hours programming today.

    public class UserManagerRepository : IUserManagerRepository, IDisposable
    {
        private readonly Entities _context = new Entities();
        private bool _disposed;
    
        public User Create(User user, int countryId)
        {
            user.Country = GetCountry(countryId);
            _context.AddToUser(user);
            _context.SaveChanges();
            return user;
        }
    }
    

    Then to use this repository I do something like:

    using(var repository = new UserManagerRepository())
    {
        repository.Create(user);
    }
    

提交回复
热议问题