MVC 3 EF 4.1 dbContext - Deleting one-to-many data object with non-nullable foreign-key relation

前端 未结 4 1125
梦毁少年i
梦毁少年i 2021-02-07 11:46

I am using MVC 3, EF 4.1, and dbContext. I need to know how to delete an entity in one-to-many relation with a non-nullable foreign-key.

When I Remove the child entity

4条回答
  •  北恋
    北恋 (楼主)
    2021-02-07 12:40

    I managed to solve the problem as follows:

    First, I was able to fetch the ObjectContext by casting my DbContext (eg "ctx") to an IObjectContextAdapter and then obtaining reference to the ObjectContext.

    Next, I simply called the DeleteObject method passing the UserContact record to be deleted.

    When SaveChanges gets the deletes in the database happen as expected.

    if (c.isDeleted == true)  // Deleted UserContact
    {
        ObjectContext oc = ((IObjectContextAdapter)ctx).ObjectContext;
        oc.DeleteObject(uc)
    }
    

    Here is a snippet of the relevant code:

    foreach (var c in model.Contacts)
    {
        UserContact uc = null;
        if (c.UserContactId != 0)
        {
            uc = ctx.UserContacts.Find(c.UserContactId);
        }
        if (uc != null)
        {
            if (c.isDeleted == true)  // Deleted UserContact
            {
                ObjectContext oc = ((IObjectContextAdapter)ctx).ObjectContext;
                oc.DeleteObject(uc);
            }
            else  //  Modified UserContact
            {
                uc.userContactData = c.ContactData;
                uc.userContactTypeId = c.ContactType;
                ctx.Entry(uc).State = EntityState.Modified;
            }
        }
        else  // New UserContact
        {
            usr.UserContacts.Add(new UserContact { userContactData = c.ContactData, userContactTypeId = c.ContactType });
        }
    }
    
    ctx.Entry(usr).State = EntityState.Modified;
    ctx.SaveChanges();
    

    Hope this helps someone in future.

提交回复
热议问题