2013-07-22 50 views
0

數據庫中的所有表都有一個名爲「r_e_c_n_o_」的列,不是一個自動增量列,並且不可能改變它。我們的ERP數據庫來自第三家公司,他們用他們的方法創建數據庫。EF從非通用dbset中返回下一個值

所以......我需要的是自動遞增的SaveChanges中的()值的方法,目前I'm使用下面的方法如下泛型方法:

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; 
     } 

回答

2

可以使entityType一個實例,然後調用你原來的通用擴展方法:

使用非泛型類型,像(看註釋行)相同210
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>(); 
}