1

New to params object[]...and would like to try a suggestion from Returning a DataTable using Entity Framework ExecuteStoreQuery

How to pass these parameters (guid gId, string sName) to a stored procedure using Entity Framework? This is what I want to try, cause, I need to return a data table.

public DataTable ExecuteStoreQuery(string commandText, params Object[] parameters)
{
   DataTable retVal = new DataTable();
   retVal = context.ExecuteStoreQuery<DataTable>(commandText, parameters).FirstOrDefault();    
   return retVal;
}
Community
  • 1
  • 1
Ruby
  • 949
  • 7
  • 31
  • 68
  • 1
    The whole **point** of using Entity Framework is so you **don't have to** mess around with `DataTable` and columns / rows - but instead you can work with nice .NET objects instead! Stop trying to kludge EF into returning a `DataTable` ! Change your design to be able to work with entities (and collections thereof) – marc_s Nov 05 '13 at 19:09

2 Answers2

3

As the question/answer you linked to tells you, ExecuteStoreQuery returns entities - it cannot return a DataTable.

You could use it to return a collection of entities, then turn that into a DataTable using 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;
}

As far as params goes, that just lets you string values together in your method call instead of packaging them up in an object[]:

DataTable dt = ExecuteStoreQuery("SELECT * FROM...", guid, sName);
D Stanley
  • 149,601
  • 11
  • 178
  • 240
-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

is the idea but your going to want to pass SQL params so...

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

or more liner for me so I can see better

        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);
MichaelEvanchik
  • 1,748
  • 1
  • 13
  • 23