EF从非通用dbset返回下一个值

本文关键字:返回 下一个 dbset EF | 更新日期: 2023-09-27 18:24:18

数据库中我的所有表都有一个名为"r_e_c_n_o_"的列,不是自动递增的列,也不可能更改它。这是我们的ERP数据库,来自第三家公司,他们使用自己的方法创建数据库。

所以。。。我需要的是一个通用方法来自动增加savechanges()方法中的值,目前我正在使用以下方法:

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

EF从非通用dbset返回下一个值

您可以创建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>();
}