So, I’m beggining to use EF, and I’m developing an application using it as ORM. The thing is I haven’t had much time to dig into the documentation (I Plan to, in due time)and I’m kind of lost in some things. For example, I have these two queries:
public static int GetNextPadlockNumber()
{
LockersDBEntities1 entities = new LockersDBEntities1();
var query = (from p in entities.PadLocks select p.PadlockNumber).DefaultIfEmpty(0).Max();
return (int)query + 1;
}
public static Data.PadLock GetPadLockByNumber(int number)
{
Data.LockersDBEntities1 entities = new LockersDBEntities1();
var query = (from p in entities.PadLocks where p.PadlockNumber == number select p).FirstOrDefault();
return query;
}
and
public static int GetNextLockerNumber()
{
LockersDBEntities1 entities = new LockersDBEntities1();
var query = (from l in entities.Lockers select l.LockerNumber).DefaultIfEmpty(0).Max();
return (int)query+1;
}
public static Data.Locker GetLockerByNumber(int number)
{
Data.LockersDBEntities1 entities = new LockersDBEntities1();
var query = (from l in entities.Lockers where l.LockerNumber == number select l).FirstOrDefault();
return query;
}
And the thing is They’re Exactly the same query. Isn’t there Any way to do this without having to specify that I want a locker or a padlock? Thanks in advance heroes.
One of the great things with EF is that you can do things like that. It’s not trivial, and it will take some trial and error, but you can abstract a lot of the database complexities away.
Now, assuming that
LockersDBEntities1is aDbContext, you could something like this:and use it like:
and
The
getNumberExpressionexpression is needed because there is no common way to access the number across all entities. It might be overdesign, but if that is an issue I would do something like this:and implement that interface on
Locker,Padlockand other classes that need to provide lock numbers. Then, in the method above the expression can be omitted, and a generic constraint can be used, like: