我有两张表Lesson
和Group
。
我有4节课和2组,所有课程都在第一组(grp_Id=1
)。
组:
public partial class Group:IEntity
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Group()
{
this.Lessons = new HashSet<Lesson>();
}
public int Id { get; set; }
public Nullable<int> Ex_Id { get; set; }
public string Name { get; set; }
public Nullable<int> Factor { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Lesson> Lessons { get; set; }
public EntityState EntityState { get; set; }
}
课:
public partial class Lesson:IEntity
{
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
public Lesson()
{
}
public int Id { get; set; }
public Nullable<int> Grp_Id { get; set; }
public string Name { get; set; }
public Nullable<int> FromNum { get; set; }
public Nullable<int> ToNum { get; set; }
public Nullable<int> CountQuestio { get; set; }
public Nullable<int> Factor { get; set; }
public virtual Group Group { get; set; }
public EntityState EntityState { get; set; }
}
我使用本手册来实现具有实体框架Link
的n层图层为了保存和修改,我使用这种方法:
public virtual void Update(params T[] items)
{
using (var context = new AzmaEntities())
{
DbSet<T> dbSet = context.Set<T>();
foreach (T item in items)
{
dbSet.Add(item);
foreach(DbEntityEntry<IEntity> entry in context.ChangeTracker.Entries<IEntity>())
{
IEntity entity = entry.Entity;
entry.State = GetEntityState(entity.EntityState);
}
}
context.SaveChanges();
}
}
这是我更新外键和更新课程的示例代码;在使用Id=3
查找课程时,请更改该论坛并更新Grp_Id
:
IGroupBLL grpbll = new GroupBLL();
IList<Group> grps = new List<Group>();
grps = grpbll.GetAllGroupWithLesson();
foreach (Group grp in grps)
{
foreach (Lesson lsn in grp.Lessons)
{
if(lsn.Id == 3)
{
lsn.EntityState = EntityState.Modified;
lsn.Grp_Id = 2;
break;
}
}
}
grpbll.UpdateGroup(grps.ToArray());
问题:
在运行grpbll.UpdateGroup(grps.toArray())
grp_id之前更改为2
运行UpdateGroup
后,运行Update
方法。在Update
方法运行下面的代码后,将grp_Id更改为1(旧的grp_Id为1)
DbSet<T> dbSet = context.Set<T>();
foreach (T item in items )
{
dbSet.Add(item);
foreach(DbEntityEntry<IEntity> entry in context.ChangeTracker.Entries<IEntity>())
{
IEntity entity = entry.Entity;
entry.State = GetEntityState(entity.EntityState);
}
}
问题:
如何更新lesson
中的外键?如何更改课程仅在组中更改grp_Id
?
答案 0 :(得分:0)