首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >DbUpdateExecption-保存不为其关系公开外键属性的实体时出错

问DbUpdateExecption-保存不为其关系公开外键属性的实体时出错
EN

Stack Overflow用户
提问于 2013-06-05 12:00:54
回答 1查看 3.9K关注 0票数 1

我的Asp.net Mvc4应用程序有问题。

我设计了一个“用户”表和一个“可投射的”,并且有一个多到多的关系。

我的用户表:

代码语言:javascript
复制
 public partial class User
{
    public User()
    {
        this.Role = new HashSet<Role>();
        this.Project = new HashSet<Project>();
    }

    public int Id { get; set; }
    public string Username { get; set; }
    public string Password { get; set; }

    public virtual ICollection<Role> Role { get; set; }
    public virtual ICollection<Project> Project { get; set; }
}

我的项目表:

代码语言:javascript
复制
public partial class Project
{
    public Project()
    {
        this.Thresholds = new HashSet<Thresholds>();
        this.User = new HashSet<User>();
        this.Testrelease = new HashSet<Testrelease>();
    }

    public int Id { get; set; }
    public string Name { get; set; }

    public virtual ICollection<Thresholds> Thresholds { get; set; }
    public virtual ICollection<User> User { get; set; }
    public virtual ICollection<Testrelease> Testrelease { get; set; }
}

在我的项目-主计长中:

代码语言:javascript
复制
public ActionResult EditProject(int id = 0)
    {
        Project project = db.Project.Find(id);
        if (project == null)
        {
            return HttpNotFound();
        }
        List<CheckBoxListInfoInt> userCheck = new List<CheckBoxListInfoInt>();
        foreach (User U in db.User.ToList())
        {
            userCheck.Add(new CheckBoxListInfoInt
            {
                ValueInt = U.Id,
                DisplayText = U.Username,
                IsChecked = (project.User.Contains(U))
            });
        }
        ViewBag.P_usrCB = userCheck;
        ViewData["pid"] = id;
        return View(project);
    }

    //
    // POST: /KPI_Data/Edit/5

    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult EditProject(Project project)
    {
        if (ModelState.IsValid)
        {
            db.Project.Attach(project);

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

            if (project.User.Count > 0)
                project.User.Clear();


            List<string> usrlist = new List<string>();
            var ucb = Request.Form["P_usrCB"];
            if (ucb != null)
                foreach (string item in ucb.Split(','))
                {
                    int UserId = Convert.ToInt32(item);
                    User usr = db.User.Single(x => x.Id == UserId);
                    project.User.Add(usr);
                    usrlist.Add(usr.Username);
                }
            db.SaveChanges();
            return RedirectToAction("Index");
        }
        return View(project);
    }

错误发生在

db.SaveChanges();

在我的HttpPost ActionMethod里

错误信息是:

保存不为其关系公开外键属性的实体时发生错误。EntityEntries属性将返回null,因为无法将单个实体标识为异常的源。通过在实体类型中公开外键属性,可以更容易地处理保存过程中的异常。有关细节,请参阅InnerException。

为什么我会有这个错误?解决办法是什么?thx

EN

回答 1

Stack Overflow用户

发布于 2013-06-05 13:26:31

避免使用db.Entry(ptvm.place).State = EntityState.Modified;,因为它会导致并发冲突而没有更新。对多个关系而不是两个表使用ViewModel。

您必须使用UpdateModel(table object, "model");

完整的例子如下:

代码语言:javascript
复制
[HttpPost]
public ActionResult PlaceTag(PlacesWithTagsViewModel model)
{
    if (ModelState.IsValid)
    {
       tag tagtest = GetTagById(model.tagid);
       tag.name= model.tag.name;
       tag.nameplural = model.tag.nameplural;
       UpdateModel(tag, "model");
       db.SaveChanges();
       return RedirectToAction("Index", "Dashboard", new { id = 5 });
    } 
}

UpdateModel的优点是您只需要提到那些您更新的字段,避免那些仍然是静态的字段。通过这种方式,您可以在编辑视图中使用Viewmodel更新相关数据。

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16939410

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档