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

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 2, 20262026-06-02T03:32:44+00:00 2026-06-02T03:32:44+00:00

I’m having lots of trouble with codefirst Entity Framework. I have a database with

  • 0

I’m having lots of trouble with codefirst Entity Framework.

I have a database with two tables – Users and Countries. Users has a field that has a foreign key of CountryId. When a user is first added to the database the FK is updated fine. However, if I try to update the FK on a user that I attach to a new DbContext, no changes happens.

I can update the FK in the context that I originally created the user in. Also, I can update the FK in a context where I retrieve the user from the database. However, in a context where I just Attach the user, the FK field does not update, even though normal nvarchar or int fields do update.

Here is my DbContext:

class DataContext : DbContext
{
    public DbSet<User> Users { get; set; }
    public DbSet<Country> Countries { get; set; }
}

And here is my model:

public class User
{
    public int UserId { get; private set; }
    public string Name { get; set; }
    public virtual Country Country { get; set; }

}

public class Country
{
    public int CountryId { get; private set; }
    public string Name { get; set; }
}

This method demonstrates the problem. I add 3 users to my database, and then try to modify them in 3 different ways – in the original context the user was added in, in a new context with Attach, and and in new context where the user is retrieved back from the database to modify:

static void Main(string[] args)
{
    Country[] countries;

    using (var dc = new DataContext())
    {
        countries = dc.Countries.ToArray();
    }

    var u = new User();

    // FIRST ROW
    using (var dc = new DataContext())
    {
        u.Name = "First";
        u.Country = countries[0];
        dc.Users.Attach(u);
        dc.Entry(u).State = System.Data.EntityState.Added;
        dc.SaveChanges();

        u.Name = "FirstChanged";
        u.Country = countries[1];
        // defaults to 'added' once u is tracked.
        dc.Entry(countries[1]).State = EntityState.Unchanged; 
        dc.SaveChanges();
    }

    // SECOND ROW
    u = new User();
    using (var dc = new DataContext())
    {
        u.Name = "Second";
        u.Country = countries[0];
        dc.Users.Attach(u);
        dc.Entry(u).State = System.Data.EntityState.Added;
        dc.SaveChanges();
    }

    using (var dc = new DataContext())
    {
        u.Name = "SecondChanged";
        u.Country = countries[1];
        dc.Users.Attach(u);
        dc.Entry(u).State = System.Data.EntityState.Modified;
        dc.SaveChanges();
    }

    // THIRD ROW
    u = new User();
    using (var dc = new DataContext())
    {
        u.Name = "Third";
        u.Country = countries[0];
        dc.Users.Attach(u);
        dc.Entry(u).State = System.Data.EntityState.Added;
        dc.SaveChanges();
    }

    using (var dc = new DataContext())
    {
        u = dc.Users.Find(u.UserId);
        u.Name = "ThirdChanged";
        u.Country = countries[1];
        dc.Entry(countries[1]).State = EntityState.Modified;
        dc.SaveChanges();
    }
}

This application produces the following results in the database:

UserId  Name    Country_CountryId   
------------------------------------------------------------------------
1   FirstChanged    2
2   SecondChanged   1
3   ThirdChanged    2

As you can see, In all cases Name is successfully updated. In the first case and third case, the CountryId is updated. However, in the second case the CountryId is not updated. Unfortunately, this is case is most relevant for me, as I want to be able to persist the Model for editing by a user outside of a DataContext.

I don’t understand why this is happening – if the Name field did not update I could understand, but as its just CountryId I can’t work out why. In both cases the Country object is tracked and marked as Unchanged. I can’t understand why only the second case doesn’t work.

Please help me work out what is up here. The only solution I can think of is to use the third case when I need to modify, so that when I save I copy across data from my persisted object to a new object retrieved from the database which is saved… but obviously this is a silly solution.

Below, I include a console application that demonstrates this problem. To run it you will need to retrieve EntityFramework using NuGet (or similar) and a connection string like this:

<add name="DataContext" connectionString="DataSource=.\DataContext.sdf" providerName="System.Data.SqlServerCe.4.0" />

Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using System.Data;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            Country[] countries;

            using (var dc = new DataContext())
            {
                countries = dc.Countries.ToArray();
            }

            var u = new User();

            // FIRST ROW
            using (var dc = new DataContext())
            {
                u.Name = "First";
                u.Country = countries[0];
                dc.Users.Attach(u);
                dc.Entry(u).State = System.Data.EntityState.Added;
                dc.SaveChanges();

                u.Name = "FirstChanged";
                u.Country = countries[1];
                // defaults to 'added' once u is tracked.
                dc.Entry(countries[1]).State = EntityState.Unchanged;
                dc.SaveChanges();
            }

            // SECOND ROW
            u = new User();
            using (var dc = new DataContext())
            {
                u.Name = "Second";
                u.Country = countries[0];
                dc.Users.Attach(u);
                dc.Entry(u).State = System.Data.EntityState.Added;
                dc.SaveChanges();
            }

            using (var dc = new DataContext())
            {
                u.Name = "SecondChanged";
                u.Country = countries[1];
                dc.Users.Attach(u);
                dc.Entry(u).State = System.Data.EntityState.Modified;
                dc.SaveChanges();
            }

            // THIRD ROW
            u = new User();
            using (var dc = new DataContext())
            {
                u.Name = "Third";
                u.Country = countries[0];
                dc.Users.Attach(u);
                dc.Entry(u).State = System.Data.EntityState.Added;
                dc.SaveChanges();
            }

            using (var dc = new DataContext())
            {
                u = dc.Users.Find(u.UserId);
                u.Name = "ThirdChanged";
                u.Country = countries[1];
                dc.Entry(countries[1]).State = EntityState.Modified;
                dc.SaveChanges();
            }
        }
    }

    class DataContext : DbContext
    {
        public DbSet<User> Users { get; set; }
        public DbSet<Country> Countries { get; set; }

        public DataContext()
        {
            Database.SetInitializer<DataContext>(new ModelInitializer());
            Database.Initialize(false);
        }
    }

    class ModelInitializer : DropCreateDatabaseAlways<DataContext>
    {
        protected override void Seed(DataContext context)
        {
            var jsds = new List<Country>
                {
                    new Country("United Kingdom"),
                    new Country("United States Of America")
                };

            jsds.ForEach(jsd => context.Countries.Add(jsd));
        }
    }

    public class User
    {
        public int UserId { get; private set; }
        public string Name { get; set; }
        public virtual Country Country { get; set; }

    }

    public class Country
    {
        public int CountryId { get; private set; }
        public string Name { get; set; }

        public Country() { }

        public Country(string name)
        {
            Name = name;
        }
    }
}

Thanks for looking at this question – any help would be appreciated. I’m on the second day of trying to fix it and I am slowly going crazy…

  • 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-06-02T03:32:45+00:00Added an answer on June 2, 2026 at 3:32 am

    This is tricky problem based on the difference between foreign key association vs independent association. If you use foreign key association (you will have CountryId property in your User entity) your second case will work as well but you are using independent association where the association itself has its own state which must be set to Added to make it work. DbContext doesn’t offer API to change the state of the association so you must use ObjectContext.

    u = new User();
    using (var dc = new DataContext())
    {
        u.Name = "Second";
        u.Country = countries[0];
        dc.Users.Attach(u);
        dc.Entry(u).State = System.Data.EntityState.Added;
        dc.SaveChanges();
    }
    
    using (var dc = new DataContext())
    {
        u.Name = "SecondChanged";
        u.Country = countries[1];
        dc.Users.Attach(u);
        ObjectContext oc = ((IObjectContextAdapter)dc).ObjectContext;
        oc.ObjectStateManager.ChangeObjectState(u, EntityState.Modified);
        oc.ObjectStateManager.ChangeRelationshipState(u, countries[1], x => x.Country, EntityState.Added);
        dc.SaveChanges();
    }
    

    When you use independent associations you can find a lot of complications.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

link Im having trouble converting the html entites into html characters, (&# 8217;) i
I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I'm having trouble keeping the paragraph square between the quote marks. In firefox the
I have a reasonable size flat file database of text documents mostly saved in
That's pretty much it. I'm using Nokogiri to scrape a web page what has
I have just tried to save a simple *.rtf file with some websites and
I want to count how many characters a certain string has in PHP, but
I have a jquery bug and I've been looking for hours now, I can't
Basically, what I'm trying to create is a page of div tags, each has

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.