如何通过亚音速的对象从连接的表中返回数据?



我在亚音速3上使用ActiveRecord,我想有效地做到这一点:

  select * from foo
   left outer join bar on bar.Id = foo.barId
where foo.someProperty = 2

我已经写了一个存储过程来获取数据,但亚音速只创建了对象来保存foo和bar的列。

将数据返回到单个对象中以便我可以绑定它的最佳方法是什么?理想情况下,我希望它是在一个列表<>,但没有写我自己的类,似乎没有亚音速提供的方式。

这里有几个选项…

您可以创建一个数据库视图来执行连接,并让SubSonic为您的视图生成一个数据类型,然后您的选择将像从任何其他表中选择一样。

或者,您可以使用Linq表达式来连接到匿名或动态类型(如果您使用的是。net 4)。例如:

public List<dynamic> LoadData(int id)
{
  var data = from f in db.Foo
             from b in db.Bar.Where(x => x.Id == f.BarId).DefaultIfEmpty()
             where f.SomeProperty == id
             select new
             {
               SomeProperty = f.Something,
               AnotherProperty = b.SomethingElse
             };
  return data.Cast<dynamic>().ToList();
}

当然,另一种选择是执行上面的Linq表达式,但要定义自己的类来保存返回的数据,并在其中进行选择。

public class MyData
{
  public string SomeProperty { get; set; }
  public string AnotherProperty { get; set; }
}
public List<MyData> LoadData(int id)
{
  var data = from f in db.Foo
             from b in db.Bar.Where(x => x.Id == f.BarId).DefaultIfEmpty()
             where f.SomeProperty == id
             select new MyData()
             {
               SomeProperty = f.Something,
               AnotherProperty = b.SomethingElse
             };
  return data.ToList();
}

最新更新