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

Thom
15.3k34 gold badges117 silver badges201 bronze badges
asked Mar 27, 2014 at 12:22

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) }
);
answered Mar 27, 2014 at 12:40
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())
{ 
 ...
} 
answered Mar 27, 2014 at 12:35

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();
answered Mar 27, 2014 at 12:38

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.

answered Mar 27, 2014 at 13:03

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.