I have this code but it doesn't work :
public bool DeleteAccess(int _UserID, IEnumerable<int> _ModulID)
{
MPortalContext db=new MPortalContext();
foreach (var item in _ModulID)
{
var validation = db.WebSite_PermissionDB.Where(x => x.UserID == _UserID && x.ModuleID == item);
db.WebSite_PermissionDB.Remove(validation);
}
db.SaveChanges();
return true;
}
my (_ModulID) is a collection of ids that i filter them and then with foreach delete them but it doesn't work ??
one way to delete is
context.Database.SqlQuery<WebSite_PermissionDB>(
"DELETE FROM Users WHERE UserID = @userId ",
new [] { new SqlParameter("@userId ", 1) }
);
First get the all entities that mathces with your condition, then use RemoveRange
method:
var entities = db.WebSite_PermissionDB
.Where(x => x.UserID == _UserID && _ModulID.Contains(x.ModuleID));
db.WebSite_PermissionDB.RemoveRange(entities);
db.SaveChanges();
Also you might want to use using
statement in order to make sure that your DbContext
is Disposed
properly.
using(MPortalContext db = new MPortalContext())
{
...
}
var distinctResult = db.WebSite_PermissionDB.Distinct();
db.WebSite_PermissionDB.RemoveRange(db.WebSite_PermissionDB.Except(distinctResult));
db.SaveChanges();
MPortalContext db=new MPortalContext();
foreach (var item in _ModulID)
{
var validation = db.WebSite_PermissionDB.Where(x => x.UserID == _UserID && x.ModuleID == item).FirstOrDefault();
db.WebSite_PermissionDB.Remove(validation);
db.SaveChanges();
}
return true;
I forget use .FirstOrDefault();
now correct. Thank friends.
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.