实体框架无法删除具有关系的对象

时间:2013-07-18 07:52:33

标签: entity-framework entity

我有两张表格,关系是1:1。我使用实体框架的模型第一种方法创建它们。现在我想删除一条记录,但是当我尝试获得以下异常时,我无法从一个表中删除而不能从另一个表中删除:

'正在从AssociationSet' FK_lm_ab_profile_lm_profile_master'添加或删除关系。对于基数约束,相应的< lm_ab_profile'也必须添加或删除。'

我有一个与ABProfile有关系的个人资料表,我想从个人资料和AbProfile中删除。他们都使用profile_id作为PK,而ABProfile使用profile_id作为FK

我的代码:

        //Get the old profile to see if one already exists
            var oldProfile = context.lm_profile_master.FirstOrDefault(p => p.profile_id.Equals(profileID));

            lm_ab_profile ab = new lm_ab_profile();

            //Check to see if user doesn't already exist
            if (oldProfile != null)
            {

                    //try and specify the relationship between profile and ABProfile using profileID
                    oldProfile.lm_ab_profileReference.EntityKey = new System.Data.EntityKey("luminusEntities.lm_ab_profile", "profile_id", profileID);    


                    //remove found object from the database and persist changes  

                    context.DeleteObject(oldProfile);
                    context.SaveChanges();
              }

我如何指定两个表是相关的,所以当我从一个删除一个记录时,另一个记录也被删除...我为模型上的级联功能设置了我的表。

1 个答案:

答案 0 :(得分:0)

您描述的情况是表格之间的约束。你试图影响一致性。

查看此Delete an object and all of its related entities in Entity Framework并定义ON DELETE CASCADE

相关问题