C# 发布以在MVC中使用模型进行编辑

C# 发布以在MVC中使用模型进行编辑,c#,model-view-controller,controller,C#,Model View Controller,Controller,p.C.我刚开始学习这个在保存更改之前添加这个 {db.WinchesBrands.Where(w => w.WinchBrandName == model.WinchBrandName) // .Update();} 它会将您的条目标记为已修改,EF会对其进行更新 db.Entry(model).State = EntityState.Modified; 这是正确的实体类型WinchModel不是当前上下文模型的一部分。创建数据库后是否更新了模型类?您是

p.C.我刚开始学习这个

在保存更改之前添加这个

{db.WinchesBrands.Where(w => w.WinchBrandName == model.WinchBrandName)
            //    .Update();}
它会将您的条目标记为已修改,EF会对其进行更新

db.Entry(model).State = EntityState.Modified;

这是正确的

实体类型WinchModel不是当前上下文模型的一部分。创建数据库后是否更新了模型类?您是否执行了迁移,数据库中是否有包含WinchModel的表?我更新了模型类,但没有执行任何迁移。我的数据库中有WinchModel的表。那么,尝试执行迁移和更新数据库。您的异常“实体类型WinchModel不是当前上下文的模型的一部分。”表示EF已连接到数据库,但未找到任何与模型相关的表,请执行编辑。
{db.WinchesBrands.Where(w => w.WinchBrandName == model.WinchBrandName)
            //    .Update();}
db.Entry(model).State = EntityState.Modified;
 if (ModelState.IsValid)
        {
            WinchesBrand winch = new WinchesBrand
            {
                WinchBrandId = model.WinchBrandId.Value,
                WinchBrandName = model.WinchBrandName
            };
            db.Entry(winch).State = EntityState.Modified;

            var ropeToDelete = db.Ropes
                .Where(r => r.IdWinch == model.WinchBrandId 
                    && !model.RopeList.Contains(r.RopeId))
                    .ToList();
            foreach(var rope in ropeToDelete){
                rope.IdWinch = null;
            }

            foreach (var ropeId in model.RopeList.Where(w => w > 0))
            {
                var rope = new Rope { RopeId = ropeId.Value };
                db.Ropes.Attach(rope);
                rope.IdWinch = winch.WinchBrandId;
            }

            await db.SaveChangesAsync();
            return RedirectToAction("Index");
        }