1

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...

Oliver
  • 11,297
  • 18
  • 71
  • 121

1 Answers1

5

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.

Community
  • 1
  • 1
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670
  • I just want to say that your answers to many EF-related questions have been invaluable to me. Thank you. – John H Apr 17 '12 at 12:31
  • Thanks for your answer. I tried the code that you posted but had some trouble with it (I got an error saying to refresh the `ObjectStateManager`, but doing so meant that `u.Name` did not update, though the FK did...), so I changed my `Users` class to use foreign key association. I then changed my code to assign countries like this: `u.CountryId = countries[0].CountryId;`. Is this correct? It seems to work, but in certain cases the `Country` property is null rather than reflecting the `CountryId` property of the User. – Oliver Apr 17 '12 at 13:15
  • Yes it is correct way to use FK associations. The name wasn't updated because the code is missing the line to change state of user to modified. I will update the code. – Ladislav Mrnka Apr 17 '12 at 13:51