添加记录时mvc4 DB更新异常

时间:2015-02-18 04:59:51

标签: asp.net-mvc-3 asp.net-mvc-4

我无法修复此错误,我有一个名为 profile 的模型,我有时会向该模型添加记录,并且工作正常。然而,我在模型配置文件的末尾添加了另一个模型,现在它给了我一个更新例外

  public class profile 

{
   [Key]
  public  int ID { get; set; }
  public string name { get; set; }
    public following follows { get; set; }
}

正如您所看到的,我在最后添加了公开跟随,因为这样我就可以更轻松地将dapper ORM与嵌入的模型一起使用。我遇到的问题是,在向个人资料模型中添加新记录时,由于公开跟随,我有任何方法可以修复此?

                     model.name="John Doe";
                    db.profiles.Add(model.profile);
                    db.SaveChanges();

看到上面的代码总是被执行但不是因为它声明公跟随符不能为空,我怎么能让它可以为空呢?

以下模型的另一个原因是

    public class following
{

    [Key]
    public int ID { get; set; }
    public int? me { get; set; }
    public int? ProfileID { get; set; }

}

我的数据库异常错误说 Follows_ID 不能为空。

这是完整的代码

             [HttpPost]
        public ActionResult Register(homepage model)
        {

                     model.name="John Doe";
                    db.profiles.Add(model.profile);
                    db.SaveChanges();
                return RedirectToAction("complete");

    }

1 个答案:

答案 0 :(得分:0)

您正在获取该异常,因为您正在实例化Following但未设置ID。但即使将{id}添加到Following模型后,您仍会遇到此问题。我愿意你做model.follows = null;这应该可以解决错误。

相关问题