即使数据未保存在DB中,也会更新绑定

时间:2016-01-07 10:33:02

标签: c# wpf

我有一个包含服务器的数据库(现在为虚拟数据),其中包含要ping的IP地址。 ping成功后,服务器状态将设置为online。

我运行了应用程序,并且应用程序和数据库中都显示了更改。所以我觉得一切都很好。

直到我将保存注释到数据库部分。实际上,更改不会保存到数据库中。但是,更改确实显示,因此我的绑定会更新。

我希望应用程序中显示的数据与数据库匹配。因此,当保存到DB失败时,应用程序数据不会更改,应用程序和数据库仍然匹配。

这是代码,我希望你可以帮助我:)。

// Get all servers that have an IP adress.
var query =
   from server in dataEntities.Server
   where server.IPAdress != null
   select server;

// Ping the servers from the query.
foreach (Server server in query)
{
    IPAdress = server.IPAdress;
    Boolean online = checkPing.sendPing(IPAdress);
    // Change the status according to the ping result.
    if (online == true)
        server.Status = true;
    else if (online == false)
        server.Status = false;
}

// Save the changes in status in the DB.
/*try
{
    dataEntities.SaveChanges();
}
catch (Exception oops)
{
    Console.WriteLine(oops);
    // Provide for exceptions.
}*/

1 个答案:

答案 0 :(得分:2)

如果SaveChanges失败,那么您需要将实体的值回滚到原来的值。

DbContext课程中,您可以添加名为Rollback的方法,它看起来像这样:

public class MyDbContext : DbContext
{
    //DataSets and what not.
    //...

    public void Rollback()
    {
        //Get all entities
        var entries = this.ChangeTracker.Entries().ToList();

        var changed = entries.Where(x => x.State != EntityState.Unchanged).ToList();
        var modified = changed.Where(x => x.State == EntityState.Modified).ToList();
        var added = changed.Where(x => x.State == EntityState.Added).ToList();
        var deleted = changed.Where(x => x.State == EntityState.Deleted).ToList();

        //Reset values for modified entries
        foreach (var entry in modified)
        {
            entry.CurrentValues.SetValues(entry.OriginalValues);
            entry.State = EntityState.Unchanged;
        }

        //Remove any added entries
        foreach (var entry in added)
            entry.State = EntityState.Detached;

        //Undo any deleted entries
        foreach (var entry in deleted)
            entry.State = EntityState.Unchanged;
    }
}

您只需在catch

中调用此方法即可
try
{
    dataEntities.SaveChanges();
}
catch (Exception oops)
{
    //Rollback all changes
    dataEntities.Rollback();
}

请注意,INotifyPropertyChanged将需要在绑定到视图的属性上实现,这将确保回滚执行的任何更改都将被推回到视图。