0

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 ??

4 Answers 4

2

one way to delete is

context.Database.SqlQuery<WebSite_PermissionDB>(
  "DELETE FROM Users WHERE UserID = @userId  ",
  new [] { new SqlParameter("@userId ", 1) }
);
Sign up to request clarification or add additional context in comments.

Comments

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())
{ 
     ...
} 

1 Comment

In my code : dont know RemoveRange & Contains . But i use nameSpaces :using System.Data.Entity; & using System.Data.Objects.DataClasses; ??but dont know.
0
var distinctResult = db.WebSite_PermissionDB.Distinct();
db.WebSite_PermissionDB.RemoveRange(db.WebSite_PermissionDB.Except(distinctResult));
db.SaveChanges();

2 Comments

Could you add some explanation for what this code sample does to your answer?
first select data by removing duplicate rows(Distinct method), then remove all rows unless selected data (Except method) in previous code.
0
    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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.