0

I stumbled on a problem after a migration from EF4.1 to EF6.

To simplify I created the example below. The problem is that on the call ctx.SaveChanges(); p.CityId gets populated with the correct value, but not p.CityId2.

If after the creation of the City entity I call the ctx.SaveChanges() the p.CityId2 is set correctly.

On EF4.1 the code below sets the p.CityId2correctly without the intermediate ctx.SaveChanges().

Any idea why this happens and what I should do in this case except the intermediate ctx.SaveChanges(). Why does EF correctly propagates the CityId but not the CityId2 ?

class Program
{
    static void Main(string[] args)
    {
        using (MyContext ctx = new MyContext())
        {
            City c = new City() { Id2 = 32767 };
            ctx.Set<City>().AddOrUpdate(c);

            Person p = new Person() { Id2 = 32767 };
            p.City = c;
            ctx.Set<Person>().AddOrUpdate(p);

            ctx.SaveChanges();
        }
    }
}

class City
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public int Id2 { get; set; }
}

class Person
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int Id { get; set; }
    public int Id2 { get; set; }

    public int CityId { get; set; }
    public int CityId2 { get; set; }
    public City City { get; set; }
}

internal sealed class CityConfiguration : EntityTypeConfiguration<City>
{
    public CityConfiguration()
    {
        HasKey(t => new { t.Id, t.Id2 });
    }
}

internal sealed class PersonConfiguration : EntityTypeConfiguration<Person>
{
    public PersonConfiguration()
    {
        HasKey(t => new { t.Id, t.Id2 });
    }
}

class MyContext : DbContext
{
    public MyContext()
    {
        Database.SetInitializer(new DropCreateDatabaseIfModelChanges<MyContext>());
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Configurations.Add(new CityConfiguration());
        modelBuilder.Configurations.Add(new PersonConfiguration());
    }
}
Andrei Gavrila
  • 853
  • 9
  • 19
  • Huh? Why would you use a composite primary key where one of its components is an identity column? An identity column is already unique by itself. –  Aug 07 '15 at 11:27
  • the database is replicated. the second id is an sql instance id. – Andrei Gavrila Aug 07 '15 at 13:02

1 Answers1

0

Have you checked this thread

composite key as foreign key ?

Maybe you're missing something like following in Person configuration?

.HasForeignKey(p => new {p.CityId, p.CityId2});
Community
  • 1
  • 1
VV01K
  • 21
  • 3
  • hi, yes. but EF is smart enough to know that the 2 ids are a composite FK. I did implicitly declare the FK but that does not help. `HasRequired(t => t.City).WithMany().HasForeignKey(fk => new { fk.CityId, fk.CityId2 });` – Andrei Gavrila Aug 12 '15 at 12:34