[英]How can I delete multiple rows with Entity Framework?
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 ?? 我的(_ModulID)是ID的集合,我对其进行过滤,然后使用foreach删除它们,但是它不起作用?
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: 首先获取符合条件的所有实体,然后使用
RemoveRange
方法:
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
的语句,以确保您DbContext
被Disposed
正常。
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();
我忘了使用
.FirstOrDefault();
now correct. 现在正确。 Thank friends.
谢谢朋友。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.