善!请解释行为EntityFrameWork:
创建模型:
public class Types
{
[Key]
public int Id {get; set;}
public string Name {get; set;}
public virtual ICollection<ControlCheck> ControlChecks {get; set;}
}
public ControlCheck
{
[Key]
public int Id {get;set;}
public string Data {get; set;}
public virtual ICollection<Types> CheckTypes {get; set;}
}
public partial class ModeMy : DbContext
{
public ModeMy()
: base("name=ConnectionString")
{
}
...........
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Types>()
.HasMany<ControlCheck>(cc => cc.ControlChecks)
.WithMany(c=>c.CheckTypes)
.Map(cc=>
{
cc.MapLeftKey("ControlCheckType_Id");
cc.MapRightKey("ControlChecks_Id");
cc.ToTable("ControlCheckTypeControlChecks");
});
}
}
接下来,在周期中添加条目:
ModeMy context = new ModeMy();
......
while (someCondition)
{
List<Types> selectedTypes = new List<Types>();
selectedTypes.Add(context.Types.Where(t=>t.Name.Contains("a")).Single());
selectedTypes.Add(context.Types.Where(t=>t.Name.Contains("b")).Single());
selectedTypes.Add(context.Types.Where(t=>t.Name.Contains("c")).Single());
selectedTypes.Add(context.Types.Where(t=>t.Name.Contains("d")).Single());
ControlCheck newCheck = new ControlCheck
{
Name = "SomeName",
CheckTypes = selectedTypes
}
context.ControlCheck.Add(newCheck);
context.SaveChanges();
}
......
当组织多对多实体创建一个额外的表来修复记录的关系时,但是当在环路外创建上下文实例时,向ControlCheck表添加记录只更新关系表中的一些记录,而它应创建新记录,问题解决了当创建Context进入循环时,在这种情况下,在ControlCheck中添加的每个新记录都会反映在表关系中。 为什么会这样?为什么我不能使用在循环外创建的cantext实例?
Thanx!