不可数之间的关系

时间:2012-03-18 07:04:44

标签: c#

我有一个关于实体的简单问题。 我有一个简单的方法,它在db中的两个表之间进行简单的内连接, 现在返回的类型是匿名的,我认为, 如果我使用IEnumerable像下面它工作正常,当我填充datagridview它工作正常,但我如何在IEnumerable和检索我的对象之间移动,因为他们是匿名类型,我们不能使用这个:

foreach(var o in result)
 o.Id //did not have a type and is not accessible

????? Testmethod()
{
  IEnumerable<object> result;

   using (var context = new TestDBEntities())
    {


         result = (from a in context.Table1
              join b in context.Table2
                  on a.ID equals b.Id
              select new { b.Id ,b.name });
           }

 return ???
 } 

1 个答案:

答案 0 :(得分:5)

你不能在方法之间传递匿名类型(你可以,但不是强类型,它最好是一个糟糕的解决方法)。最好的方法是为您定义一个可以在投影中使用的简单类:

public class Foo
{
   public int Id {get;set;}
   public string Name {get;set;}
}

现在,您可以在查询中使用Foo并返回IEnumerable<Foo>作为结果:

IEnumerable<Foo> Testmethod()
{
    using(var context = new TestDBEntities())
    {
         var result = (from a in context.Table1
                       join b in context.Table2
                       on a.ID equals b.Id
                       select new Foo() { Id = b.Id , Name = b.name });
         return result.ToList();//force materializing results
    }
 }
相关问题