从Entity框架返回自定义对象并分配给对象数据源

我需要一些问题的指导,我正在使用Entity Framework 4.0,我有一个DAL和BLL并且在页面上绑定到ObjectDataSource。

我不得不使用PIVOT和动态SQL编写存储过程,以便按照我想要的方式从多个实体返回数据。 现在我想弄清楚如何让Entity Framework返回一个我可以绑定到页面上的ObjectDataSource的自定义对象,我需要使用自定义对象或动态对象,因为存储过程可以返回任意数量的列所以我不能使用强类型类或实体,我还需要能够将它与ObjectDataSource绑定。

有人能指出一个很好的方法来做这个以及如何定义我的function? 请提供一些代码示例。

我读到我应该尝试使用List返回一个对象,因为EF不支持返回数据表/数据集,到目前为止我有以下内容,但我知道这是不正确的。

我没有太多使用仿制药,如果你能指出如何做到这一点,我相信这对很多人都有帮助。 请提供该函数的代码示例以及如何将ObjectDataSource绑定到返回对象?

非常感谢您的帮助!

感谢您的帮助Richard根据您对使用DbDataRecord的建议,这就是我现在的function

DAL中ObjectDataSource C#函数

 public List GetData(int product_id) { List availableProducts = new List(); var groupData = context.ExecuteStoreQuery("exec spGetProducts @ProductID={0}", product_id); availableProducts = groupData.ToList(); return availableProducts; } 

ASPX页面中的ObjectDataSource

      

现在,当我访问页面时,我收到此错误:

结果类型“System.Data.Common.DbDataRecord”可能不是抽象的,必须包含默认构造函数

这是因为ExecuteStoreQuery期望被定义为类还是实体? 如何根据存储过程结果创建一个对象并将其分配给它?

如果您已经拥有与proc返回类型匹配的实体类型,请将其用作类型参数。

 public List GetData(int product_id) where T : class { List myList = new List(); var groupData = context.ExecuteStoreQuery("exec spGetProductsByGroup @ProductID={0}", product_id); return myList; } 

否则,您可以使用ADO.NET DataReader手动构建列表。

 using (SqlConnection connection = new SqlConnection("your connection string")) { SqlCommand command = new SqlCommand( "exec spGetProductsByGroup @ProductID", connection); command.Parameters.Add(product_id); connection.Open(); SqlDataReader reader = command.ExecuteReader(); List list = new List(); if (reader.HasRows) { while (reader.Read()) { list.Add(new ProcType(){Property1 = reader.GetInt32(0), Property1 = reader.GetString(1)); } } reader.Close(); return list; } 

这样的事情怎么样:

 using (AdventureWorksEntities context = new AdventureWorksEntities()) { string myQuery = @"SELECT p.ProductID, p.Name FROM AdventureWorksEntities.Products as p"; foreach (DbDataRecord rec in new ObjectQuery(myQuery, context)) { Console.WriteLine("ID {0}; Name {1}", rec[0], rec[1]); } } 

如果你想用GridView呈现结果,那么实际上你几乎就在那里 – 使用绑定和AutoGenerate列,因为ObjectQuery是一个IEnumerable。 我正在使用ObjectQuery,但您可以将它与ExecuteStoreQuery交换 – 因为它们都返回IEnumerable

 string myQuery = @"SELECT p.Name,p.VatNumber FROM MyEntities.Users as p"; ProductList.ItemsSource = new ObjectQuery(myQuery, context); 

在XAML中

  

并且您将看到直接在UI中返回的列。

如果您没有使用WPF并且想要一个元素列表 ,那么您需要做的就是:

 var myList = new ObjectQuery(myQuery, context).ToList(); 

或采取你原来的方法,它将是:

 var myList = context.ExecuteStoreQuery("exec spGetProductsByGroup @ProductID={0}", product_id); 

如果你确实需要迭代字段; 然后以下将做的伎俩:

 foreach (var rec in context.ExecuteStoreQuery("exec spGetProductsByGroup @ProductID={0}", product_id)) { for (var ri = 0; ri < rec.FieldCount;ri++) { Console.WriteLine(rec.GetDataTypeName(ri) +" " + rec.GetName(ri) +" = " + rec.GetValue(ri)); } } 

LINQ和Generics的众多优点之一是,大多数情况下,在最终到达需要处理它们的位置之前,您不必过多担心实际的数据类型。