由于一个或多个外键属性不可为空,因此无法更改关系

时间:2014-07-06 16:48:13

标签: c# entity-framework foreign-keys try-catch dbcontext

我有gridview。这个网格视图包含大量记录(会员信息)。

   try
            {
                Member member=new Member();
                IdMember = int.Parse(gvListCompany.SelectedRows[0].Cells[0].Value.ToString());


                member = objMemberRepository.FindBy(i => i.Id == IdMember).First();
                objMemberRepository.Delete(member);
                objMemberRepository.Save();


                toolStripStatusLabelLine.Visible = true;
                lblState.Text = "delete is successfully";
                StatusMain.BackColor = Color.Green;

                gvListCompany.DataSource = objMemberRepository.FindBy(i => i.IsSupporter == typeofmember).ToList();
            }
            catch
            {
                toolStripStatusLabelLine.Visible = true;
                lblState.Text = "couldn't delete because of subset records";
                StatusMain.BackColor = ColorTranslator.FromHtml("#ea0000");
                return;

            }

这是一个删除网格视图项的代码。假设我要删除另一个表中有FK item的记录,这样就无法删除记录,并且try语句会抛出异常,如果我尝试删除其他表中没有任何error的记录,我会在此操作后向用户显示正确的this record has an subset please delete the subset {i} {i}}我可以'删除,但实际上我应该能够删除,因为我的记录在其他表中没有任何FK记录。

错误消息

FK

会员班:

The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.

我将我的代码更改为此并且有效,但我真的不知道为什么?

   public partial class Member
    {
        public Member()
        {
            this.Inovices = new HashSet<Inovice>();
        }
        public int Id { get; set; }
        public string Type { get; set; }
        public string Name { get; set; 
        public string EconomicCompnayNumber { get; set; }
        public string IntNumber { get; set; }
        public string Province { get; set; }
        public string City { get; set; }
        public string PostCode { get; set; }
        public string Address { get; set; }
        public string PhoneNumber { get; set; }
        public string Region { get; set; }
        public string IsSupporter { get; set; }

        public virtual ICollection<Inovice> Inovices { get; set; }
        public virtual ICollection<Cash> Cashes { get; set; }
}

我认为是因为dbcontext。

祝你好运

0 个答案:

没有答案