ExecuteStoreQuery EntityFramework

时间:2013-11-05 18:27:12

标签: c# entity-framework-4

params对象[]的新功能...并想尝试Returning a DataTable using Entity Framework ExecuteStoreQuery

的建议

如何使用Entity Framework将这些参数(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;
}

2 个答案:

答案 0 :(得分:3)

当您链接的问题/答案告诉您时,ExecuteStoreQuery会返回实体 - 它无法返回DataTable

可以使用它来返回实体集合,然后使用DataTable将其转换为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);

答案 1 :(得分:-3)

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