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

前端 未结 4 1150
梦毁少年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:28

    I solved the same problem following the section "Cascade Delete Rules on Relationships" at the MSDN guide page here http://msdn.microsoft.com/en-us/library/bb738695.aspx Hope tu be helpfull :D

    0 讨论(0)
  • 2021-02-07 12:31

    You can configure the relation to cascade ... this will propagate the delete to dependent entities.

    But it's very dangerous :)

    I prefer setting a flag in the row that prevents the data tier from including it in future queries, most applications do not need physical delete (and will be a chance to undo).

    0 讨论(0)
  • 2021-02-07 12:39

    well, implement your own ICollection and mark those child objects for deletion along with removing it. And then, in your own SaveChanges method override, delete those objects.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题