当Initializer.Seed()
使用DbContext.DbSet.Find()
设置新代理的导航属性时,它会正确地将FK分配给代理,但第一个导航属性始终为null我打破SaveChanges()
并检查代理。有谁知道为什么会这样做?
(抱歉,我无法发布本地窗口的屏幕截图。)
模型
public class Thing : Base {
public virtual Nullable<int> Option1ID { get; set; }
public virtual Option1 Option1 { get; set; }
public virtual Nullable<int> Option2ID { get; set; }
public virtual Option2 Option2 { get; set; }
public virtual Nullable<int> Option3ID { get; set; }
public virtual Option3 Option3 { get; set; }
}
public class Option1 : Base {
public virtual ICollection<Thing> Things { get; set; }
}
public class Option2 : Base {
public virtual ICollection<Thing> Things { get; set; }
}
public class Option3 : Base {
public virtual ICollection<Thing> Things { get; set; }
}
public class Base {
public virtual int Id { get; set; }
public virtual string Name { get; set; }
}
的DbContext
public class Context : DbContext {
public DbSet<Thing> Things { get; set; }
public DbSet<Option1> Option1s { get; set; }
public DbSet<Option2> Option2s { get; set; }
public DbSet<Option3> Option3s { get; set; }
public ObjectContext ObjectContext {
get { return ((IObjectContextAdapter)this).ObjectContext; }
}
protected override void OnModelCreating(DbModelBuilder modelBuilder) {
base.OnModelCreating(modelBuilder);
}
}
种子()
var option1s = new List<Option1> {
new Option1{Name="Red"},
new Option1{Name="Green"}};
option1s.ForEach(x => db.Option1s.Add(x));
db.SaveChanges();
var option2s = new List<Option2> {
new Option2{Name = "Tall"},
new Option2{Name = "Short"}};
option2s.ForEach(x => db.Option2s.Add(x));
db.SaveChanges();
var option3s = new List<Option3> {
new Option3{Name = "Male"},
new Option3{Name = "Female"}};
option3s.ForEach(x => db.Option3s.Add(x));
db.SaveChanges();
var thing = db.Things.Create();
thing.Option1 = db.Option1s.Find(1); //the first thing.XXXX shows null no matter what order
thing.Option2 = db.Option2s.Find(1); //but the FK's work for all three of them
thing.Option3 = db.Option3s.Find(1);
db.Things.Add(thing);
db.SaveChanges();
答案 0 :(得分:0)
哇。我不知道你在那里做了什么,但你让对象状态跟踪器非常生气。
修改强>
我认为这是调试器中的某种错误以及它与动态代理一起使用的方式。我这样说是因为你可以Console.WriteLine(thing.Option1.Id);
,它会给你正确的ID。如果通过说var thing = new Thing();
来摆脱动态代理,则调试器问题就会消失。
这是您尝试做的更标准的方法。
var option1s = new List<Option1> {
new Option1{Name="Red"},
new Option1{Name="Green"}};
option1s.ForEach(x => db.Option1s.Add(x));
var option2s = new List<Option2> {
new Option2{Name = "Tall"},
new Option2{Name = "Short"}};
option2s.ForEach(x => db.Option2s.Add(x));
var option3s = new List<Option3> {
new Option3{Name = "Male"},
new Option3{Name = "Female"}};
option3s.ForEach(x => db.Option3s.Add(x));
var thing = db.Things.Create();
thing.Option1 = option1s[0];
thing.Option2 = option2s[0];
thing.Option3 = option3s[0];
db.Things.Add(thing);
db.SaveChanges();