我的 DataContext 有问题。在下面的代码片段中,我首先删除数据上下文中的现有对象,然后在相同的代码中再次添加新对象。问题是,由于我正在使用 .DeleteOnSubmit() 它在我的 Datacontext 中仍然包含 2 个实体,因此它正确存储在我的数据库中。
这里的代码:
public void ConnectedApartment(Apartment newApartment, Apartment existing)
{
ConApart ConApartTemp = new ConApart();
ConApartTemp.Apartment1 = newApartment;
ConApartTemp.Apartment = existing;
DatabaseConnection.ConAparts.InsertOnSubmit(ConApartTemp);
}
public void opdaterConApart(ArrayList connected, Apartment Apartmenten)
{
foreach (ConApart sam in Apartmenten.ConAparts)
{
DatabaseConnection.ConAparts.DeleteOnSubmit(sam);
}
foreach (ConApart sam2 in Apartmenten.ConAparts1)
{
DatabaseConnection.ConAparts.DeleteOnSubmit(sam2);
}
foreach (Apartment apa in connected)
{
ConnectedApartment(apa, Apartmenten);
}
DatabaseConnection.SubmitChanges();
}
如果我之前没有 SubmitChanges() 的删除
foreach (Apartment apa in connected)
{
ConnectedApartment(apa, Apartmenten);
}
然后我的 Datacontext 将包含 2 个实体,我的 gui 将在每次更改时显示重复项。
如果我使用以下内容:
public void ConnectedApartment(Apartment newApartment, Apartment existing)
{
ConApart ConApartTemp = new ConApart();
ConApartTemp.Apartment1 = newApartment;
ConApartTemp.Apartment = existing;
DatabaseConnection.ConAparts.InsertOnSubmit(ConApartTemp);
}
public void opdaterConApart(ArrayList connected, Apartment Apartmenten)
{
foreach (ConApart sam in Apartmenten.ConAparts)
{
DatabaseConnection.ConAparts.DeleteOnSubmit(sam);
}
foreach (ConApart sam2 in Apartmenten.ConAparts1)
{
DatabaseConnection.ConAparts.DeleteOnSubmit(sam2);
}
DatabaseConnection.SubmitChanges();
foreach (Apartment apa in connected)
{
ConnectedApartment(apa, Apartmenten);
}
DatabaseConnection.SubmitChanges();
}
然后它可以工作,但是对于回滚功能,该解决方案很弱,因为它会: 1. 删除现有对象 2. submitChanges 3. 添加新对象 4. submitChanges
但是,如果在第 2 点和第 3 点之间出现故障,被删除的对象就会丢失。有什么建议么?我怎样才能维护我的上下文,所以它不会挂在双实体上,并且如果出现问题仍然可以处理回滚功能???