I have this code in my controller:
public ActionResult Details(int id)
{
开发者_如何学C using (var db = new MatchGamingEntities())
{
var MyMatches = from m in db.Matches
join n in db.MatchTypes on m.MatchTypeId equals n.MatchTypeId
where m.MatchId == id
select new MatchesViewModel
{
MatchType = n.MatchTypeName,
MatchId = m.MatchId,
MatchName = m.MatchTitle,
MatchDescription = m.MatchDescription,
Wager = m.Wager
};
ViewBag.MyMatches = MyMatches.ToList();
return View(MyMatches.ToList());
}
}
I want to be able to make this query only return a single result and I can use MyMatches as a MatchesViewModel object so I do not have to use the ToList()
feature thus getting rid of the IEnumberable on the view page @model IEnumerable<MatchGaming.Models.MatchesViewModel>
so I can turn it into this: @model MatchGaming.Models.MatchesViewModel
You can call the appropriately named extension method Enumerable.Single()
.
Here are some other related methods and the differences between them depending on how many elements there are in the collection you are querying:
No elements More than one element First Throws exception First element returned FirstOrDefault default(T) First element returned Single Throws exception Throws exception SingleOrDefault default(T) Throws exception
.Single() will return the one object. If there's more than one, or none, it'll throw an exception.
.First() will just give you the first, only throwing an exception when there are no items.
.FirstOrDefault() is the same as .First(), but giving you NULL when there are no items.
I usually use .UniqueResult<>(). It returns the single result or a null reference.
精彩评论