在Linq中删除查询

时间:2010-04-26 23:40:06

标签: c# linq linq-to-sql

我有这个简单的代码,但它显示错误。我不知道我哪里错了。 我在最后一行显示错误..“DeleteOnSubmit” linq_testDataContext db = new linq_testDataContext();

var remove = from aremove in db.logins
         where aremove.username == userNameString && aremove.Password == pwdString
         select aremove;
db.logins.DeleteOnSubmit(remove);

6 个答案:

答案 0 :(得分:4)

DeleteOnSubmit只占用一个对象。您正在向其传递IEnumerable<login>。请改用DeleteAllOnSubmit,或从结果集合中选择一个对象,如下所示:

var remove = (from aremove in db.logins 
             where aremove.username == userNameString 
                && aremove.Password == pwdString 
             select aremove).FirstOrDefault(); 

if(remove != null)
{
    db.logins.DeleteOnSubmit(remove);
}

答案 1 :(得分:4)

你缺少foreach循环来删除所有实体。

使用如下

var remove = from aremove in db.logins
     where aremove.username == userNameString && aremove.Password == pwdString
     select aremove;

之后

foreach (var detail in remove)
{
    db.logins.DeleteOnSubmit(detail);
}

最后

 try
{
    db.SubmitChanges();
}
catch (Exception e)
{
    // Provide for exceptions.
}

希望这会对你有所帮助。

答案 2 :(得分:2)

而不是:

db.logins.DeleteOnSubmit(remove);

拨打DeleteAllOnSubmit(),如下所示:

db.logins.DeleteAllOnSubmit(remove.ToList());

请务必事后致电db.SubmitChanges()。您也可以使用.AsEnumerable(),或者。如果它是一个大的删除操作,你可能想要考虑在这种情况下绕过LINQ。

答案 3 :(得分:0)

尝试使用first()方法,如下所示:

var remove = 
    (from aremove in db.logins where aremove.username == userNameString 
    && aremove.Password == pwdString select aremove).first();

db.logins.DeleteOnSubmit(remove);

答案 4 :(得分:0)

使用此代码进行工作

var remove = (from aremove in db.logins 
             where aremove.username == userNameString 
                && aremove.Password == pwdString 
             select aremove).FirstOrDefault(); 

if(remove != null)
{
     db.logins.Remove(remove);
     db.SaveChanges();
}

答案 5 :(得分:0)

有关良好做法

 private void DeleteCourse()
        {
            int id = Convert.ToInt32( txtSearch.Text);
            CourseDemoDataContext cdContext = new CourseDemoDataContext();
            course courseobj = cdContext.courses.Single(courses => courses.COURSE_ID == id);
            cdContext.courses.DeleteOnSubmit(courseobj);
            cdContext.SubmitChanges();
        }