I start deal with LINQ To SQL and I try sol开发者_StackOverflow中文版ve this primitive problem. I have very simple table with two columns.
- Nick - key, unique
- Password
I would like delete row with some nick value.
I use this method:
public void DeleteSpiritUser(string nick)
{
var user = from u in _dc.Spirit_Users where u.Nick == nick select u;
using (var scope = new TransactionScope())
{
_dc.Spirit_Users.DeleteOnSubmit(user.First());
try
{
_dc.SubmitChanges();
}
catch (Exception exception)
{
throw exception;
}
scope.Complete();
}
}
Problem is that I must use user.First() if I want one single row, I would like select with LINQ only one row know IEnumerable, because Nick is unique.
Try this - just select only the first (if present), and only delete if you got a value:
public void DeleteSpiritUser(string nick)
{
var user = (from u in _dc.Spirit_Users
where u.Nick == nick
select u).SingleOrDefault();
if(user != null)
{
using (var scope = new TransactionScope())
{
_dc.Spirit_Users.DeleteOnSubmit(user);
_dc.SubmitChanges();
scope.Complete();
}
}
}
You can do:
var user = _dc.Spirit_Users.Single(u => u.Nick == nick);
Well First() is the one that will extract the first (and only) row (plus it will add TOP 1 to query). Linq2Sql doesn't know that you only have one row (or that you'll have any at all) and is preparing to receive more than one, thus IEnmuerable even when there is one row.
精彩评论