Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/csharp-4.0/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 4.0 如何将删除的实体回滚到其以前的状态?_C# 4.0_Entity Framework 4.1 - Fatal编程技术网

C# 4.0 如何将删除的实体回滚到其以前的状态?

C# 4.0 如何将删除的实体回滚到其以前的状态?,c#-4.0,entity-framework-4.1,C# 4.0,Entity Framework 4.1,考虑以下情况: public class EntityA { public int Id { get; set; } } public class EntityB { public int Id { get; set; } public virtual EntityA EntityA { get; set; } } public class Context : DbContext { public Context() : base("EF_S

考虑以下情况:

public class EntityA
{
    public int Id { get; set; }
}

public class EntityB
{
    public int Id { get; set; }

    public virtual EntityA EntityA { get; set; }
}

public class Context : DbContext
{
    public Context()
        : base("EF_SPIKE")
    {
    }

    public IDbSet<EntityA> EntityAs { get; set; }

    public IDbSet<EntityB> EntityBs { get; set; } 
}

static void Main(string[] args)
{
    using (var context = new Context())
    {
        var a = context.EntityAs.Create();
        context.EntityAs.Add(a);

        var b = context.EntityBs.Create();
        b.EntityA = a;
        context.EntityBs.Add(b);

        context.SaveChanges();

        using (var transaction = new TransactionScope())
        {
            context.EntityBs.Remove(b);
            context.SaveChanges();
        }

        Trace.Assert(b.EntityA == null);
        Trace.Assert(context.EntityBs.Local.All(x => x.Id != b.Id));
        Trace.Assert(context.EntityBs.Any(x => x.Id == b.Id));
    }
}

通过?

我认为除了在第一次
SaveChanges()
后存储其Id并在回滚后重新获取它之外,没有其他方法。我假设在现实生活中,您会有条件地回滚,并且之后仍然希望向我们提供一个实体?您仍然拥有保留在实体中的Id。是,在回滚发生后,我仍然希望使用实体。我现在正在事务完成事件中重新填充它,只是想知道是否有更好的方法。
Trace.Assert(context.EntityBs.Local.Any(x => x.Id == b.Id));