Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6167399
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 23, 20262026-05-23T22:30:20+00:00 2026-05-23T22:30:20+00:00

I am using MVC 3, EF 4.1, and dbContext. I need to know how

  • 0

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 and execute SaveChanges I get the error:

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.

From other posts, I understand that using Remove(entity) marks the entity for delete. During SaveChanges, EF sets the the foreign-key to Null and the above error occurs.

I have found some posts that use DeleteObject on the child entity rather than Remove; however, the DeleteObject approach seems to have been dropped because of addition to dbContext and DbSet.

I have found posts that suggest modifying the EDMX foreign-key relation to be Nullable. Modifying the EDMX is fine, but whenever an Update Model for Database is done, these changes get nuked and must be reapplied. Not optimal.

Another post suggested creating a proxy entity with the foreign-key relations set to Nullable but I do not understand that approach. It seems to suffer from the same issue as modifying the EDMX in that the context gets automatically updated when changes to the EDMX are saved.

My simplified model is:

public partial class User
{
    public User()
    {
        this.UserContacts = new HashSet<UserContact>();
    }

    public long userId { get; set; }
    public string userEmail { get; set; }
    public string userPassword { get; set; }
    public string userFirstName { get; set; }
    public string userLastName { get; set; }
     . . .
    public virtual Country Country { get; set; }
    public virtual State State { get; set; }
    public virtual ICollection<UserContact> UserContacts { get; set; }
}

}

public partial class UserContact
{
    public long userContactId { get; set; }
    public long userContactUserId { get; set; }
    public long userContactTypeId { get; set; }
    public string userContactData { get; set; }

    public virtual ContactType ContactType { get; set; }
    public virtual User User { get; set; }
}

The userContactUserId and userContactTypeId are required foreign-keys.

In the dbContext container both Users and UserContact are DbSet.

I have a ViewModel for the User and a ViewModel for UserContact as follows

public class UserContactViewModel
{
    [HiddenInput]
    public long UserContactId { get; set; }

    [HiddenInput]
    public long UserContactUserId { get; set; }

    [Display(Name = "Contact")]
    [Required]
    public string ContactData { get; set; }

    [Required]
    public long ContactType { get; set; }

    [HiddenInput]
    public bool isDeleted { get; set; }

}

    public class MyProfileViewModel
    {

        [HiddenInput]
        public long UserId { get; set; }

        [Required]
        [Display(Name = "First Name")]
        [StringLength(100)]
        public string FirstName { get; set; }

        [Required]
        [StringLength(100)]
        [Display(Name = "Last Name")]
        public string LastName { get; set; }
        ....
        public IEnumerable<UserContactViewModel> Contacts { get; set; }

}

When saving changes to the user profile, I loop over the list of UserContactViewModel entities to determine which have been added, modified, or deleted.

                    foreach (var c in model.Contacts)
                    {
                        UserContact uc = usr.UserContacts.Single(con => con.userContactId == c.UserContactId);
                        if (uc != null)
                        {
                            if (c.isDeleted == true)  // Deleted UserContact
                            {
                                ctx.UserContacts.Remove(uc);  // Remove doesn't work
                            }
                            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 { userContactUserId = model.UserId, userContactData = c.ContactData, userContactTypeId = c.ContactType });
                        }
                    }

I’d appreciate any help.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-23T22:30:22+00:00Added an answer on May 23, 2026 at 10:30 pm

    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
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

First some brief background: I have an existing ASP.NET MVC 1 application using Entity
The goal: I'm trying to use the new Entity Framework 4.1 DbContext API (using
I am Using MVC 3.0 My issue is on one page I am using
Using MVC with an observer pattern, if a user action requires polling a device
I've been using MVC frameworks for a short while now and I really like
I'm using MVC to validate some html text boxes on a page, for example
Have you tried using MVC or any other UI pattern for GWT client code.
Just getting started using MVC in ASP.NET, I'm going to have it so users
I am developing an application using MVC Preview 5. I have used typed views.
I'm trying to get better at using MVC/MVP style patterns with my WinForm apps

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.