使用 DataContext 获取单个项目

发布于 2024-08-07 03:41:00 字数 492 浏览 4 评论 0原文

我正在执行以下操作:

public MyItem FetchSingleItem(int id)
{
  string query = "SELECT Something FROM Somewhere WHERE MyField = {0}";
  IEnumerable<MyItem> collection = this.ExecuteQuery<MyItem>(query, id);
  List<MyItem> list = collection.ToList<MyItem>();
  return list.Last<MyItem>();
}

这实际上并不是很优雅,我希望有更好的方法可以使用 DataContext 获取单个项目。我从我的存储库中的 DataContext 进行扩展。在你问之前有一个合理的理由,但这不是这个问题的重点;)

那么,有更好的方法吗?

干杯

I'm doing the following:

public MyItem FetchSingleItem(int id)
{
  string query = "SELECT Something FROM Somewhere WHERE MyField = {0}";
  IEnumerable<MyItem> collection = this.ExecuteQuery<MyItem>(query, id);
  List<MyItem> list = collection.ToList<MyItem>();
  return list.Last<MyItem>();
}

It's not very elegant really and I was hoping there's something a little better to get a single item out using DataContext. I'm extending from DataContext in my repository. There's a valid reason why before you ask, but that's not the point in this question ;)

So, any better ways of doing this?

Cheers

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

掌心的温暖 2024-08-14 03:41:00

如果是 SQL Server,请将 SQL 更改为:

SELECT TOP 1 Something FROM Somewhere ...

或者,将这些行更改

List<MyItem> list = collection.ToList<MyItem>();
return list.Last<MyItem>();

为这一行:

return collection.First();

If it is SQL Server, change your SQL to:

SELECT TOP 1 Something FROM Somewhere ...

Or alternatavely, change these lines

List<MyItem> list = collection.ToList<MyItem>();
return list.Last<MyItem>();

into this one:

return collection.First();
总以为 2024-08-14 03:41:00
myDataContext.MyItem.Where(item => item.MyField == id)
    .Select(item => item.Something)
    .FirstOrDefault();
myDataContext.MyItem.Where(item => item.MyField == id)
    .Select(item => item.Something)
    .FirstOrDefault();
清泪尽 2024-08-14 03:41:00

返回的记录未定义,因为您没有 ORDER BY。所以很难做出准确的翻译。不过,一般来说,颠倒顺序并采用 First():

var q = from s in this.Somewhere
        where s.MyField == id
        orderby s.Something desc
        select s.Something;
return q.First();

关系表是无序的。因此,如果您没有精确指定所需的记录,则必须将返回的记录视为随机选择的。

The record returned is undefined, since you have no ORDER BY. So it's hard to do an exact translation. In general, though, reverse the order and take the First():

var q = from s in this.Somewhere
        where s.MyField == id
        orderby s.Something desc
        select s.Something;
return q.First();

Relational tables are unordered. So if you don't specify the record you want precisely, you must consider the returned record as randomly selected.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文