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;
}
}
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 .
You can use extension method of Linq to delete the records.
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();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.