2011-07-13 113 views

回答

12
Entities.Customer.First(c => c.CustomerId == 20); 
+0

我可能錯過了一些東西。這裏是我得到的:Project1.OrderEntities oe = new Project1.OrderEntities(); oe.Customers.First(c => c.CustomerId == 20);那裏沒有財產「第一」。 – user194076

+2

'First'是一個Linq擴展方法。把'using System.Linq;'放在你的.cs文件的頂部。 –

9

您將要使用.First()或.FirstOrDefault()。區別在於,如果您的客戶不存在,是否需要空值或異常。

如果數據庫中沒有匹配結果,.First()方法將引發異常。如果沒有匹配的結果在數據庫中

Customer customer21 = oe.Customers.First(c => c.CustomerId == 20); // throws an exception if customer 21 does not exist 

Customer customer21 = oe.Customers.FirstOrDefault(c => c.CustomerId == 20); // null if customer 21 does not exist 
0

你也可以使用一個LINQ方法的.FirstOrDefault()方法將返回null,如下:

Customer customerRecord = 
    (from customer in Entities.Customers 
    where customer.id == 20 
    select customer).FirstOrDefault(); 

使用FirstOrDefault()將返回null如果帶有該ID的元素不存在,而不是First(),這會引發異常。另外,在使用LINQ語句之前,請確保包含using System.Linq;

希望這會有所幫助。