1

params object[] 的新手...并想尝试使用实体框架 ExecuteStoreQuery 返回 DataTable的建议

如何guid gId, string sName使用实体框架将这些参数()传递给存储过程?这是我想尝试的,因为我需要返回一个数据表。

public DataTable ExecuteStoreQuery(string commandText, params Object[] parameters)
{
   DataTable retVal = new DataTable();
   retVal = context.ExecuteStoreQuery<DataTable>(commandText, parameters).FirstOrDefault();    
   return retVal;
}
4

2 回答 2

3

正如您链接到的问题/答案告诉您的那样,ExecuteStoreQuery返回实体- 它不能返回DataTable.

可以使用它返回实体集合,然后将其转换为DataTableusing DataTableExtensions

public DataTable ExecuteStoreQuery(string commandText, params Object[] parameters)
{
   DataTable retVal;

   var entities = context.ExecuteStoreQuery<MyEntity>(commandText, parameters)
                          .Take(1); // use `Take` instead of `First` to keep it as a collection
   retVal = entities.AsEnumerable().CopyToDataTable();
   return retVal;
}

就目前params而言,这只是让您在方法调用中将值串在一起,而不是将它们打包在object[]

DataTable dt = ExecuteStoreQuery("SELECT * FROM...", guid, sName);
于 2013-11-05T18:44:03.003 回答
-4
The idea of params (which always has to be the last decalared parameter in a function can be unlimited for example

Function Foo(string s,params Object[] alist)
{
    //whatever
}

Cats cat = new Cats();//I put an object here because cat is an object, if it was ints they would all have to be ints
Foo("ok",cat);
Foo("ok", cat,cat,cat,cat,cat,cat);

are both valid

是这个想法,但你会想要传递 SQL 参数,所以......

            dt = ExecuteStoreQuery("INSERT INTO STATUS(ITEMTYPE,PRODESC) values(@ITEMTYPE,'@PRODESC')",new SqlParameter("@ITEMTYPE", 2),new SqlParameter("@PRODESC", "Obama sucks"));

或更多的衬里,这样我可以看得更清楚

        object[] obj;
        obj[0] = new SqlParameter("@ITEMTYPE", 2);
        obj[1] = new SqlParameter("@PRODESC", "Obama sucks");
        dt = ExecuteStoreQuery("INSERT INTO STATUS(ITEMTYPE,PRODESC) values(@ITEMTYPE,'@PRODESC')",obj);
于 2013-11-05T18:37:28.500 回答