0

データベース内のすべてのテーブルには「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;
        }
4

1 に答える 1

2

のインスタンスを作成して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>();
}
于 2013-07-22T14:11:55.010 に答える