简体   繁体   中英

can we call entity framework query with passing table value?

Is any way to pass the table name as a parameter and get the record from db with make generalized function

string table = "tbl_Category";
int Id  = Class.getLastId(table);

Class.aspx

 public static int getLastId(string table)
    {

        int lastID = 0;
        using (HatnEntities context = new HatnEntities())
        {
            // Fetch Id of last record from table
                var result = (from c in context.tbl_Category.OrderByDescending(u => u.Id) select new { Id = c.Id }).FirstOrDefault();
                                                  ^
//any way to use table name from parameter value"+table+"


                if (result != null)
                {
                    lastID = Convert.ToInt32(result.Id);
                }
                obj.Id = lastID + 1;
                context.tbl_Category.Add(obj);
                context.SaveChanges();

        }
        return status;
    }

Please let me know is it possible

您可以使用Set(),这需要传递表字符串参数,您必须从程序集中获取Type。

context.Set<TypeFromTableStringParameter>() ...

This is what you would have to do if you just want to be able to access any table in EF:

public static int getLastId<T>()
    where T : PrimaryKey
{
    using (HatnEntities context = new HatnEntities())
    {
        // Fetch Id of last record from table
        var result = (from c in context.Set<T>().OrderByDescending(u => u.Id) select new { Id = c.Id }).FirstOrDefault();

        var lastID = 0;
        if (result != null)
        {
            lastID = Convert.ToInt32(result.Id);
        }
        obj.Id = lastID + 1;
        context.Set<T>().Add(obj);
        context.SaveChanges();
    }

    // not sure where this comes from?
    return status;
}

public abstract class PrimaryKey
{
    public int Id { get; set; }
}

All of you Entities would need to inherit (extend) PrimaryKey in order for you to Select , Where or FirstOrDefault (etc. etc.) based on the property Id .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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