在visual studio中使用LINQ到SQL删除

本文关键字:LINQ SQL 删除 visual studio | 更新日期: 2023-09-27 17:51:18

我在visual studio中使用LINQ to SQL与我的数据库进行交互。现在我添加了添加,更改等方法到我的代码,但我不能使删除一行工作。下面是我的remove方法:

public bool removeUser(User toBeRemoved)
{
    try
    {
        theDBDataContext db = new theDBDataContext();
        UserDB u = new UserDB();
        u.username = toBeRemoved.userName;
        u.password = toBeRemoved.password;
        u.role = toBeRemoved.role;
        db.UserDBs.DeleteOnSubmit(u);
        db.SubmitChanges();
        return true;
    }
    catch (Exception e)
    {
        Log.writelog("Cannot Access DB");
        return false;
    }
}

在visual studio中使用LINQ到SQL删除

必须在删除前附加实体:

    theDBDataContext db = new theDBDataContext();
    UserDB u = new UserDB();
    u.username = toBeRemoved.userName;
    u.password = toBeRemoved.password;
    u.role = toBeRemoved.role;
    db.Orders.Attach(u, false);
    db.UserDBs.DeleteOnSubmit(u);
    db.SubmitChanges();

可以使用Linq的扩展方法删除记录。

    theDBDataContext db = new theDBDataContext();
     UserDB u = db.UserDBs.Where(u=>(u.username == toBeRemoved.userName & u.password == toBeRemoved.password & u.role==toBeRemoved.role)).FirstOrDefault(); 
     db.UserDBs.DeleteOnSubmit(u);
     db.SubmitChanges();