开发者

whats the shortest way of returning an Entity Framework object from one table based on it's name attribute?

what's the shortest way开发者_JAVA百科 of returning an Entity Framework object from one table based on it's name attribute?

So say one had a table person, with column name, what would be the quickest way to return the person object with name = "Tim" say?

e.g. context.People.Select(m => m.Name == "Tim") doesn't seem to work?


context.People.First(m => m.Name == "Tim")


Are you wanting only a single object? If you are confident there is just one item in the table that meets your criteria, you could say

context.People.Single(m => m.Name == "Tim");

If there could be more than one and you only want the first, then use the .First() extension method instead. The difference is that Single will throw an exception if more than one record matches your criteria. First simple does what it says, it will take the first of any number of records.

(Also consider the SingleOrDefault and FirstOrDefault methods if there may be no suitable records in the table.)

Edit: Apparently .Single is not supported in the Linq-To-Entities framework, but First is.


This works also... (maybe it's not the shortest way but I find it more readable)

        var person = (from p in context.People
         where p.Name == "Tim"
         select p).FirstOrDefault();
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜