我正在开发一个WPF应用程序,该程序使用Entity Framework 6.2从SQL Server Express数据库获取其数据以访问数据。有人告诉我不要使用寿命长的DbContext
,因此我修改了应用程序以使用寿命短的DbCcontext
。这意味着我在启动期间仅加载一次数据,然后再处理上下文。对于每个更新/删除/插入操作,我都会创建一个新上下文来保存更改=>短暂上下文。
现在我遇到了一个问题:当我尝试插入一个已经设置了所有导航属性的新实体时,我遇到了异常:
“ City_Houses” AssociationSet中的关系处于“已添加”状态。给定多重性约束,相应的“ City_Houses_Target”也必须处于“已添加”状态。
我写了一个示例代码,它复制了确切的错误消息,在这里您可以
参见DbContext
和我正在使用的模型类:
public class Context : DbContext
{
public DbSet<City> dbsCities { get; set; }
public DbSet<House> dbsHouses { get; set; }
public DbSet<Person> dbsPersons { get; set; }
public Context() : base(@"Server=.\SQLExpress;Database=test;Trusted_Connection=Yes;Connection Timeout=5")
{
Configuration.AutoDetectChangesEnabled = false;
Configuration.LazyLoadingEnabled = false;
Configuration.ProxyCreationEnabled = false;
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<City>().HasMany(c => c.Houses).WithRequired(c => c.City).WillCascadeOnDelete(true);
modelBuilder.Entity<House>().HasMany(p => p.Residents).WithRequired(p => p.House).WillCascadeOnDelete(true);
}
}
public class City
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<House> Houses { get; set; }
public City()
{
Houses = new List<House>();
}
}
public class House
{
public int Id { get; set; }
public int Number { get; set; }
public virtual City City { get; set; }
public virtual ICollection<Person> Residents { get; set; }
public House()
{
Residents = new List<Person>();
}
}
public class Person
{
public int Id { get; set; }
public string Firstname { get; set; }
public string Lastname { get; set; }
public virtual House House { get; set; }
public Person()
{
}
}
这是我用来保存更改的方法
private void AddCity(object sender, RoutedEventArgs e)
{
using (var ctx = new Context())
{
ctx.dbsCities.Add(new City() { Name = "New York" });
ctx.SaveChanges();
}
}
private void AddHouse(object sender, RoutedEventArgs e)
{
City c = null;
using (var ctx = new Context())
{
c = ctx.dbsCities.AsNoTracking().FirstOrDefault();
}
House h = new House() { Number = 66, City = c };
c.Houses.Add(h);
using (var ctx = new Context())
{
ctx.dbsHouses.Add(h);
ctx.Entry(h.City).State = System.Data.Entity.EntityState.Unchanged;
ctx.SaveChanges();
}
}
private void AddPeople(object sender, RoutedEventArgs e)
{
City c = null;
using (var ctx = new Context())
{
c = ctx.dbsCities.Include(x=>x.Houses.Select(h=>h.Residents)).AsNoTracking().FirstOrDefault();
}
Person p = new Person() { Firstname = "Max", Lastname = "Power" };
p.House = c.Houses.First();
c.Houses.First().Residents.Add(p);
using (var ctx = new Context())
{
ctx.dbsPersons.Add(p);
ctx.Entry(p.House).State = System.Data.Entity.EntityState.Unchanged;
ctx.SaveChanges();
}
}
仅当我致电AddPeople
时才会发生错误。我在这里做什么错了?