为什么LINQ to Entities不支持SingleOrDefault()?

时间:2022-11-24 12:49:37

Any ideas why LINQ to Entities doesn't support SingleOrDefault() but instead ask to use FirstOrDefault()?

任何想法为什么LINQ to Entities不支持SingleOrDefault()而是要求使用FirstOrDefault()?

Will SingleOrDefault() functionality be replaced? By what?

SingleOrDefault()功能会被替换吗?通过什么方式?

1 个解决方案

#1


I'm not sure why it was left out, but you can always roll your own.

我不知道为什么它被遗漏了,但你可以随时自己动手。

I found a similar response to this question on MSDN, here is an implementation based off of that code.

我在MSDN上找到了对此问题的类似响应,这是基于该代码的实现。

public static TElement SingleOrDefault<TElement>
      (this IQueryable<TElement> query)
{
    if (query.Count() == 1)
        return query.First();
    else if (query.Count() == 0)
        return null;
    else
        throw new InvalidOperationException();
}


// Use it like this

Product prod = (from p in db.Product
                where p.ProductID == 711
                select p).SingleOrDefault();

Source: MSDN

#1


I'm not sure why it was left out, but you can always roll your own.

我不知道为什么它被遗漏了,但你可以随时自己动手。

I found a similar response to this question on MSDN, here is an implementation based off of that code.

我在MSDN上找到了对此问题的类似响应,这是基于该代码的实现。

public static TElement SingleOrDefault<TElement>
      (this IQueryable<TElement> query)
{
    if (query.Count() == 1)
        return query.First();
    else if (query.Count() == 0)
        return null;
    else
        throw new InvalidOperationException();
}


// Use it like this

Product prod = (from p in db.Product
                where p.ProductID == 711
                select p).SingleOrDefault();

Source: MSDN