Asp.net删除asp.net条目

时间:2014-12-20 00:11:29

标签: c# asp.net asp.net-mvc entity-framework

我在循环中从数据库中删除条目时遇到困难。抛出InvalidOperationException。这是我的代码。

   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;
    }

2 个答案:

答案 0 :(得分:0)

看起来您只需要更新一个实体,而不应该在循环中执行此操作

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;
}

答案 1 :(得分:0)

我必须实例化Message对象的新实例。

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;



    }