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.CityId2
correctly 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());
}
}