使用带有lambda表达式的linQ删除记录

时间:2015-03-18 13:56:52

标签: c# asp.net linq entity-framework lambda

我想使用linq lambda表达式删除sql数据库的记录。我该怎么办?

这里'学生'是我的桌子和' db'是.edmx文件的对象

public bool DeleteRecord(int caurseID)
{
    studentEntities db = new studentEntities();

    int count = db.student.Where(s => s.caurse_id == caurseID).Count();

    if (count != 0)
    {
        //string subQuery = "delete from student where caurse_id=" + caurseID;
        //SqlCommand subCmd = new SqlCommand(subQuery, conn);
        //subCmd.ExecuteNonQuery();
        db.student. : For Delete, what will be goes here???
    }

    return true;
}

2 个答案:

答案 0 :(得分:6)

我从之前的建议中得到了参考。

studentEntities db_dlt = new studentEntities();
                var students = db_dlt.student.FirstOrDefault(s => s.caurse_id == caurseID);
                if (students != null)
                {
                    db_dlt.student.Remove(students);
                    db_dlt.SaveChanges();
                }

答案 1 :(得分:1)

public bool DeleteRecord(int caurseID)
{
   studentEntities db = new studentEntities();

   var students = db.student.Where(s => s.caurse_id == caurseID);


   if(students.Any()) 
   {
       db.DeleteAllOnSubmit(students);

       db.SubmitChanges();
   }

   return true;
}