I have a small question. How do i make linq aware that some columns are uniqe
fx. I have a table, with columns “ID” and “Name”
ID is auto incrementing Primary key. Name is just varchar(255)
The result of a linq like this:
from item in db.ItemSet
where item.ID == 1
select item
Im left with a IQueryable. But there can be only 1 item, with “ID”==1
How do i tell linq this.
At the moment i do this
(from item in db.ItemSet
where item.ID == 1
select item).First()
But I would consider this a “hack”…
You could use
.Single()instead of.First().However, both of those assume that the record exists and will throw an exception if no record is found. If there’s a potential for looking up a record that does not exist, you may want to consider
.FirstOrDefault()/.SingleOrDefault().Further reading: