【发布时间】:2011-07-21 22:16:43
【问题描述】:
当Initializer.Seed() 使用DbContext.DbSet.Find() 为新代理设置导航属性时,它会正确地将FK 分配给代理,但是当我中断@ 时,first 导航属性始终为空987654323@ 并检查代理。有谁知道为什么会这样?
(抱歉,我无法发布本地窗口的屏幕截图。)
型号
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; }
}
数据库上下文
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();
【问题讨论】:
-
我认为这是一个错误。我在下面添加了一个编辑。
标签: entity-framework entity-framework-4.1