Following is a save routine on existing record. What’s wrong with this? I’m using independent association
There’s no error emitted, however, the Country_CountryId field on Person table didn’t change, everything else are properly persisted. What’s wrong on the following code/approach?
public JsonResult SaveUpdate(Person p)
{
p.Country = new Country { CountryId = new Guid("EF0CD98E-7138-4757-866E-ADC3C8D216DA") };
using (var db = new TheDbContext())
{
db.Entry(p).State = System.Data.EntityState.Modified;
db.SaveChanges();
}
}
Here’s my mapper:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<Person>().HasRequired(x => x.Country)
.WithMany(x => x.Persons)
.Map(x => x.MapKey("Country_CountryId"));
modelBuilder.Entity<Person>().Property(x => x.RowVersion).IsRowVersion();
modelBuilder.Entity<Country>().HasKey(x => x.CountryId);
}
Here’s my models:
public class Country
{
public virtual Guid CountryId { get; set; }
public virtual string CountryCode { get; set; }
public virtual string CountryName { get; set; }
public virtual IList<Person> Persons { get; set; }
}
public class Person
{
public virtual Guid PersonId { get; set; }
public virtual string Username { get; set; }
public virtual string Firstname { get; set; }
public virtual string Lastname { get; set; }
public virtual byte[] RowVersion { get; set; }
public virtual Country Country { get; set; }
}
Use this instead and it will work:
Independent associations require special care because each association itself has its own state which must be configured.