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 7013121
In Process

The Archive Base Latest Questions

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

I am trying to create a new user object with a specific Role. The

  • 0

I am trying to create a new user object with a specific Role. The “Role” is an existing entity in EF. I have googled, and stackoverflowed until I am blue in the face, and I have tried all the stuff that seems to be working for everyone else. But when I try to save my new user object, it first tries to create a new “Role”, instead of just creating the new user object with a reference to the existing Role.

What am I doing wrong?

Role myRole = new Role { ID = myUser.Role.ID };
myObjectContext.Roles.Attach(myRole);
myUser.Role = myRole;

if (myUser.ID == 0)
{
    myObjectContext.Users.AddObject(myUser);
}
else
{
    if (myUser.EntityState == System.Data.EntityState.Detached)
    {
        myObjectContext.Users.Attach(myUser);
    }
    myObjectContext.ObjectStateManager.ChangeObjectState(myUser, System.Data.EntityState.Modified);
}
myObjectContext.SaveChanges(SaveOptions.None);

EDIT – AFTER MORE TESTING…

Ok.. so I have discovered some portion of the “cause” anyway. I still don’t know why it does this and need help.

Basically, there are two sets of data I am attaching to my new User object. One is the “Role” which is a FK to a Role table that contains the Role. This shows up as a navigation property on the User like “User.Role”.

The second set of data is a collection of objects called “FIPS”, which are a many-to-many relationship between the User and another table called FIPS. There is a relationship table between them, that simply contains two columns, each a foreign key to User and FIPS, respectively. The FIPS for a user are also a navigation property that is referenced like “User.FIPS”.

Here is the whole code showing the assignment of the FIPS and Role to the User object prior to saving the context.

List<string> fipsList = new List<string>();
foreach (FIPS fips in myUser.FIPS)
{
    fipsList.Add(fips.FIPS_Code);
}
myUser.FIPS.Clear();
foreach (string fipsCode in fipsList)
{
    FIPS myFIPS = new FIPS { FIPS_Code = fipsCode };
    myObjectContext.FIPSCodes.Attach(myFIPS);
    myUser.FIPS.Add(myFIPS);
}


Role myRole = new Role { ID = myUser.Role.ID };
myObjectContext.Roles.Attach(myRole);
myUser.Role = myRole;


if (myUser.ID == 0)
{
   myObjectContext.Users.AddObject(myUser);
}
else
{
   if (myUser.EntityState == System.Data.EntityState.Detached)
   {
       myObjectContext.Users.Attach(myUser);
   }
   myObjectContext.ObjectStateManager.ChangeObjectState(myUser, System.Data.EntityState.Modified);
}

myObjectContext.SaveChanges(SaveOptions.None);

I set up my watch to check the status of “myObjectContext.ObjectStateManager.GetObjectStateEntries(EntityState.Added)” to see when things were being added to this.

As soon as the first Related object is added to the User object, the second Related object that hasn’t yet been attached to the context, is added to the context with an EntityState of “Added”.

…. Gonna see if there is a way to avoid attaching the related entities to the User entity until after they have all been attached to the context.

–FOLLOWUP–
Ok.. well I changed the order of the code so that the related entities were attached to the context before being assigned to the User entity.. but as soon as the first related entity is assigned, the second related entity is shown as “added” in the ObjectStateEntries.
So, then I changed it to the following order:

  1. Attach all related entities to context.
  2. Remove existing relationships on the user object to related entity
    types.
  3. Assign related entities to user entity.
  4. Save user entity.

And.. now.. it works.. omg it works… ! =)

  • 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-27T22:20:44+00:00Added an answer on May 27, 2026 at 10:20 pm

    It’s been a while since I wrote the code below, but I vaguely recall running into the same problem and it was occurring because the role being added was currently being tracked by the context, so attaching the stub has the effect of adding a new role with the same Id.

    In the following code, I check the ChangeTracker first and use an existing entry if the role is being tracked.

    // add roles that are in dto.Roles, but not in resource.Roles
    // use the change tracker entry, or add a stub role
    var rolesToAdd = fromDto.Roles.Where(r => !toResource.Roles.Any(role => role.Id == r)).ToList();
    var roleEntries = dbContext.ChangeTracker.Entries<Role>();
    
    foreach (var id in rolesToAdd)
    {
        var role = roleEntries.Where(e => e.Entity.Id == id).Select(e => e.Entity).FirstOrDefault();
    
        if (role == null)
        {
            role = new Role { Id = id };
            dbContext.Set<Role>().Attach(role);
        }
    
        toResource.Roles.Add(role);
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I'm trying to create a new user record into OpenLDAP with object classes person
In a view I'm trying to create a new user and then log them
I am trying to create a new contact using Dynamic Entity. The sample i
I'm trying to create a new object of type T via its constructor when
I'm trying to create a new project in NetBeans PHP from existing sources. When
I'm trying to create a new object that is related to two other models
I've got a Backbone.js/Rails app and I'm trying to create a new object through
In Symfony2 RC3, I am trying to create a related entity on a User
I'm trying to create a new user on my development active directory server using
The error message below i get when Im trying to create a new user

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.