繁体   English   中英

EF从非泛型dbset返回下一个值

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM