我有一个实体假设 [MainEntity]。这个主实体有一些子实体,如下所示:
MainEntity:
-> ChildEntity1
-> ChildEntity2
-> ChildEntity3
-> ChildEntity4
-> ChildEntity5
所有子实体与主实体具有一对多的关系。
在 UI 用户更新主实体和前 3 个子实体的数据。在 UI 中 ChildEntity1、ChildEntity2、ChildEntity3 分别由 GridView、ListBox 和 CheckListBox 表示。用户可以通过这些控件添加/更新子记录。插入/更新数据的示例代码如下:
BL class:
========
public class EntityManager
{
public EntityManager ()
{
MainEntityData = new MainEntity();
}
public MainEntity MainEntityData= { get; set; }
public void InsertUpdate()
{
DAL.InsertMainEntityData(MainEntityData);
}
}
UI Codes:
=========
EntityManager objEntityManager = new EntityManager();
if (lnkInsertUpdate.CommandArgument == "Update")
objEntityManager.MainEntity.ID =
int.Parse(Request.QueryString["ID"].ToString());
objEntityManager.MainEntity.Name = txtName.Text;
objEntityManager.MainEntity.Description = txtDescription.Text;
-----------------------------------------
-----------------------------------
ChildEntity1 objChildEntity1 = null;
foreach (ListItem item in lstSelectedProduct.Items)
{
objChildEntity1 = new ChildEntity();
objChildEntity1.ClientProductID = int.Parse(item.Value);
objChildEntity1.IsActive = true;
objChildEntity1.CreatedBy = "Admin";
objChildEntity1.CreatedDate = DateTime.Now;
objEntityManager.MainEntity.ChildEntitys1.Add(objChildEntity1);
}
-----------------------------------
codes for childentity2,childentity3
--------------------------------
objEntityManager.InsertUpdate()
DALCodes:
=========
public static void InsertMainEntityData(MainEntity objMainEntity)
{
using (TransactionScope ts = new TransactionScope())
{
try
{
using (DBEntities context = DatabaseFactory.GetContext())
{
if (objMainEntity.ID > 0)
{
MainEntity mainEntityToUpdate =
context.MainEntitys.Include("ChildEntity1").Include("ChildEntity2").Include("ChildEntity3").First(o => o.ID == objMainEntity.ID);
mainEntityToUpdate = objMainEntity;
context.MainEntitys.Attach(mainEntityToUpdate);
context.ObjectStateManager.ChangeObjectState(mainEntityToUpdate,
EntityState.Modified);
}
else
{
context.AddToMainEntitys(objMainEntity);
context.SaveChanges();
ts.Complete();
}
catch (Exception ex)
{
ts.Dispose();
}
finally
{
}
}
Insert new reord 工作正常,但在更新它时给出以下错误:
ObjectStateManager 中已存在具有相同键的对象。ObjectStateManager 无法跟踪具有相同键的多个对象。
请指导如何解决这个问题??
谢谢,
保罗