![](/img/trans.png)
[英]DbSet.Cast<TEntity>() Error: Cannot create a DbSet<IEntity> from a non-generic DbSet for objects of type 'Entity'
[英]EF Return next value from a non-generic dbset
數據庫中的所有表都有一個名為“r_e_c_n_o_”的列,而不是自動增量列,並且不可能更改它。 它是我們的ERP數據庫,來自第三家公司,他們使用他們的aproach來創建數據庫。
所以...我需要的是一個自動增加savechanges()方法中的值的通用方法,目前我正在使用下面的follow方法:
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;
}
我希望使用非泛型類型實現相同的功能,例如(查看注釋行):
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;
}
您可以創建entityType
的實例,然后調用原始的通用擴展方法:
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>();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.