【问题标题】:How do I return data from joined tables through subsonic's objects?如何通过 subsonic 的对象从连接表中返回数据?
【发布时间】:2011-08-04 08:18:29
【问题描述】:

我在 Subsonic 3 上使用 ActiveRecord,我实际上想要这样做:

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

我编写了一个存储过程来获取数据,但 Subsonic 只创建了对象来保存来自 foo 和 bar 的列。

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

【问题讨论】:

  • “联合”也是我经常犯的一个错误 ;-)
  • 太棒了,谢谢。你能帮忙吗?
  • 抱歉,我什至无法弄清楚 Subsonic 是什么。我只是被你的标题吸引了。

标签: c# linq subsonic subsonic3 generics


【解决方案1】:

这里有几个选项...

您可以创建一个执行联接的数据库视图,并让 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();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-19
    • 2018-09-25
    • 1970-01-01
    相关资源
    最近更新 更多