更新记录会抛出'违反Multiplicity约束'。在asp.net mvc中

时间:2012-04-01 15:13:59

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

我正在asp.net mvc中开发一个应用程序,并首先使用EF代码进行数据访问。这是我使用的模型:

  public class Culture
    {
        [Key()]
        public int CultureID { get; set; }

        [Required()]
        [StringLength(250)]
        public string CultureName { get; set; }

        [Required()]
        [StringLength(250)]
        public string CultureDisplay { get; set; }

        public virtual List<HomePage> HomePage { get; set; }

        public virtual List<Person_Local> PersonLocal { get; set; }
    }
    public class Person
    {
        public int PersonID { get; set; }
        [StringLength(250)]
        public string PersonPicAddress { get; set; }

        public virtual List<Person_Local> PersonLocal { get; set; }
    }

    public class Person_Local
    {
        //[NotMapped()]
        [Key, Column(Order = 1)]
        [ForeignKey("Person")]
        public int PersonID { get; set; }

        [Key, Column(Order = 2)]
        [ForeignKey("Culture")]
        public int CultureID { get; set; }

        public string PersonName { get; set; }

        public string PersonFamily { get; set; }

        public string PersonAbout { get; set; }

        public virtual Culture Culture { get; set; }

        public virtual Person Person { get; set; }
    }

我没有任何问题将新人和personlocal添加到db。但是当我想更新本地人时,如下所示:

public ActionResult CreatePerson([Bind(Prefix = "Person")]Person obj,
            [Bind(Prefix = "Person.PersonLocal")]IEnumerable<Person_Local> plocals)
        {
            string photo_guid = obj.PersonPicAddress;

            if (obj.PersonID != 0)
            {
                Person p = da.Persons.FirstOrDefault(x => x.PersonID == obj.PersonID);

                TryUpdateModel(p, "Person");

                if (obj.PersonLocal[0].Person.PersonID != 0)
                {
                    int cid = obj.PersonLocal[0].Culture.CultureID;
                    int pid = obj.PersonLocal[0].Person.PersonID;

                    Person_Local ploc = 
                                      da.Person_Locals.First(x => x.CultureID == cid      && x.PersonID == pid);



                   //update ploc 


                 }

                 da.SaveChanges();
          }
}

我收到了以下错误:

违反了多重性约束。 “WebApp.Models.Person_Local_Person”关系的“Person_Local_Person_Target”角色具有多重性1或0..1。

编辑:

我发表了评论

TryUpdateModel(p, "Person");

似乎问题已经解决了?!!为什么?!

0 个答案:

没有答案