One of the great things about EF is that you can do this. This is not trivial, and it will require some trial and error, but you can abstract away many of the complexities of the database.
Now, assuming LockersDBEntities1 is a DbContext , you could have something like this:
public static class LockersDBEntities1Extensions { public static int GetNextNumber<T>( this LockersDBEntities1 context, Expression<Func<T, int>> getNumberExpression) { var query = (from item in context.Set<T> select getNumberExpression(item)) .DefaultIfEmpty(0) .Max(); return (int)query + 1; } }
and use it like:
int nextPadlockNumber = new LockersDBEntities1() .GetNextNumber<Padlock>(p => p.PadlockNumber)
and
int nextPadlockNumber = new LockersDBEntities1() .GetNextNumber<Locker>(l => l.LockerNumber)
The expression getNumberExpression necessary because there is no general way to access a number in all entities. It might be a reevaluation, but if this is a problem, I would do something like this:
and implement this interface on Locker , Padlock and other classes that should contain lock numbers. Then, in the above method, the expression can be omitted, and a general constraint can be used, for example:
public static class LockersDBEntities1Extensions { public static int GetNextNumber<T>(this LockersDBEntities1 context) where T:ILockNumberProvider { var query = (from item in context.Set<T> select item.Number) .DefaultIfEmpty(0) .Max(); return (int)query + 1; } }
Sweko source share