vertigo vertigo - 3 months ago 7
C# Question

deletion with LINQ to SQL in visual studio

I'm using LINQ to SQL in visual studio to interact with my database. Now I added methods that add, change etc to my code, but I cant make removing a row work. here is my remove method:

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;
}
}

Answer

You must attach the entity before delete:

    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();

See documentation here.

Comments