All my tables in the database has a columns named "r_e_c_n_o_", isn´t an autoincremented column, and there is no possibility to change it. Its our ERP database, from a third company and they use their aproach to create the database.
So... what I need is a generic method to increment a value in savechanges() method automatically, currently I´m using the follow method below:
public static int GetNextRecno<T>(this DbContext context) where T : DadosadvEntityBase
{
lock (_locker)
{
var typeName = typeof(T).FullName;
int next = 1;
if (lastRecnos.ContainsKey(typeName))
{
int lastRecno = lastRecnos[typeName];
next = lastRecno + 1;
}
else
{
next = context.Set<T>().Max(x => x.Recno) + 1;
}
lastRecnos[typeName] = next;
return next;
}
And I´d like to achieve the same using a non-generic type, something like (look the commented line):
public static int GetNextRecno(this DbContext context, Type entityType)
{
lock (_locker)
{
var typeName = entityType.FullName;
int next = 1;
if (lastRecnos.ContainsKey(typeName))
{
int lastRecno = lastRecnos[typeName];
next = lastRecno + 1;
}
else
{
//here is the problem with a non-generic type, I have no idea how to get next value in this case
next = context.Set<T>().Max(x => x.Recno) + 1;
}
lastRecnos[typeName] = next;
return next;
}
You can make an instance of entityType
and then call your original generic extension method:
public static int GetNextRecno(this DbContext context, Type entityType)
{
//create an instance of entityType
dynamic instance = Activator.CreateInstance(entityType);
return GetNextRecno(context, instance);
}
//note this is not an extension method
public static int GetNextRecno<T>(DbContext context, T instance)
{
//call your original generic extension method
return context.GetNextRecno<T>();
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.