C# Asp.net删除Asp.net条目
我在循环中从数据库中删除条目时遇到困难。引发InvalidOperationException。这是我的密码C# Asp.net删除Asp.net条目,c#,asp.net,asp.net-mvc,entity-framework,C#,Asp.net,Asp.net Mvc,Entity Framework,我在循环中从数据库中删除条目时遇到困难。引发InvalidOperationException。这是我的密码 public static string messageParser(string id) { ApplicationDbContext db = new ApplicationDbContext(); var ApplicationDbContext = new ApplicationDbContext(); var Use
public static string messageParser(string id)
{
ApplicationDbContext db = new ApplicationDbContext();
var ApplicationDbContext = new ApplicationDbContext();
var UserManager = new UserManager<User>(new UserStore<User>(ApplicationDbContext));
var user = UserManager.FindById(id);
string final = "";
var list = user.Message.ToList();
foreach (var item in list)
{
final += item.notification + "\n\n";
db.Message.Remove(item);
}
db.SaveChanges();
return final;
}
看起来只有一个实体需要更新,不应该在循环中更新
public static string messageParser(string id)
{
ApplicationDbContext db = new ApplicationDbContext();
var UserManager = new UserManager<User>(new UserStore<User>(db));
var user = UserManager.FindById(id);
string final = "";
var list = user.Message.ToList();
foreach (var item in list)
{
final += item.notification + "\n\n";
}
db.Message.Remove(user);
db.SaveChanges();
return final;
}
我必须建立一个消息对象的新实例
public static string messageParser(User user)
{
string final = "";
if (user != null)
{
ApplicationDbContext db = new ApplicationDbContext();
var list = user.Message.ToList();
foreach (var item in user.Message)
{
final += item.notification + "\n\n";
Message delete = db.Message.Find(item.ID);
db.Message.Remove(delete);
db.SaveChanges();
}
}
return final;
}
尝试var UserManager=newusermanagernewuserstoredb;使用ApplicationDbContextI的单个实例获取无效操作异常。EF通过更新上下文类中当前拥有的任何实体来工作。如果要更新多个实体,则需要遍历实体集,而不是用户消息列表。