Reputation: 3233
Enclosed below is an example of one of the methods that I created.
Am I correctly implementing EF6? As you can see in my commented code I first tried to create a repository class. I instead scrapped the repository class for this implementation.
However I am now getting errors because I am returning an IQueryable object and then closing the dbcontext.
So this led me to the question: Am I implementing EF6 correctly?
I could change the IQueryable to return a List<obj>
or I could remove the using (_myContext)
statement.
I'm just trying to understand the correct way to implement my methods.
public IQueryable<MY_USERS> GetAllUsers()
{
using (_myContext)
{
return _myContext.MY_USERS;
}
//MyRepository<MY_USERS> users = new MyRepository<MY_USERS>(_myContext);
//return users.GetAll();
}
Updated example:
public void DeleteUser(string userName)
{
using (var context = new MyEFConn())
{
using (var transaction = context.Database.BeginTransaction())
{
try
{
context.MY_USER_GROUPS.RemoveRange(GetUserGroups(userName));
context.MY_USERS.Remove(new MY_USERS { USER_NAME = userName });
transaction.Commit();
}
catch (Exception ex)
{
transaction.Rollback();
throw ex;
}
}
}
}
Upvotes: 4
Views: 82
Reputation: 19484
There is no no wrong or right, it just depends.
When you use IQueriable this mean that you can have common queries in your repository class and outside of it you can append additional filter.
GetAllUsers().Where(u=>u.UserType== 'Test').ToList()
You can also use include depends on your needs let say in MVC controller
GetAllUsers().Include(u=>u.Roles).Take(10).ToList();
Important thing to note, EF dont connect to db until you do ToList() or iterate throw query.
Lastly as you mentioned in comment always need to remember when you use IQuerieable that context could be disposed so this should be taken to consideration too.
On the other side could be good option return IEnumerable from repositories, so lets say if you want to load users you should have method which will require input parameters for paging, filtering or other stuff. This is useful for testing because you will be able to mock data.
About Delete it always depends on your requirements and if you need to remove all together or nothing than you need to use transactions IN addition it could be same about all CRUD.
Upvotes: 1