私は2つのテーブルLesson
とGroup
を持っています。エンティティフレームワークの更新外部キーコンテキスト.set
I 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; }
}
私はこの方法を使用し、保存し、変更するためのEntity Frameworkを持つn層の層Link
を実装するために、このマニュアルを使用します。
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());
問題:
実行UpdateGroup
後2
にgrpbll.UpdateGroup(grps.toArray())
grp_id変更を実行する前に、Update
を実行します方法。
lesson
で外部キーを更新する方法:コードの変更以下の実行後Update
方法で
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);
}
}
(旧grp_Idが1だった)1に質問をgrp_Id?レッスンの変更方法はグループ内でのみ変更するgrp_Id
?
これは解決策ではありません。 CRUDに 'Update'メソッド(上記)を使いたいと思います。 –