以下是现有记录的保存例程。这有什么问题?我正在使用independent association
没有发出错误,但是Person表上的Country_CountryId字段没有更改,其他所有字段都被正确保留。以下代码/方法有什么问题?
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();
}
}
这是我的映射器:
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);
}
这是我的模特:
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; }
}
答案 0 :(得分:1)
使用它代替,它将起作用:
public JsonResult SaveUpdate(Person p)
{
var country = new Country { CountryId = new Guid("EF0CD98E-7138-4757-866E-ADC3C8D216DA") };
using (var db = new TheDbContext())
{
db.People.Attach(p);
db.Countries.Attach(country);
db.Entry(p).State = System.Data.EntityState.Modified;
p.Country = country;
db.SaveChanges();
}
}
独立关联需要特别小心,因为每个关联本身都有自己必须配置的状态。