简体   繁体   English

如何在单元测试项目中使用Entity Framework 5回滚更改

[英]How can I roll back changes with Entity Framework 5 within a Unit Test project

I'm playing with Entity Framework, and I have a Unit Test project that I want to exercise what I've done so far. 我正在使用Entity Framework,并且我有一个单元测试项目,我想练习到目前为止所做的事情。 I'd like to have it not actually update my test database when it's done. 我希望它在完成后实际上不更新我的测试数据库。 If I was working in SQL I would create a transaction and then roll it back at the end. 如果我使用SQL,我将创建一个事务,然后在最后将其回滚。

How can I do the same thing here? 在这里我该怎么做?

As I understand it, context.SaveChanges(); 据我了解, context.SaveChanges(); is effectively doing the write to the database. 有效地进行了对数据库的写操作。 And if I don't have that, then allCartTypes is empty after I assign it context.CarTypes.ToList() 如果我没有那个,那么在我为它分配context.CarTypes.ToList()后, allCartTypes空。

Here's an example of one of my Test classes. 这是我的一个Test类的示例。

using System;
using System.Diagnostics;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Trains;
using System.Linq;

namespace TrainsTest
{
    [TestClass]
    public class TestCarType : TestBase
    {
        [TestMethod]
        public void TestCarTypeCreate_Success()
        {
            var tankerCarType = new CarType {Name = "Tanker"};
            var boxCarType = new CarType { Name = "Box" };
            using (var context = new TrainEntities())
            {
                context.CarTypes.Add(tankerCarType);
                context.CarTypes.Add(boxCarType);

                context.SaveChanges();

                var allCartTypes = context.CarTypes.ToList();
                foreach (var cartType in allCartTypes)
                {
                    Debug.WriteLine(cartType.CarTypeId + " - " + cartType.Name);
                }
            }
        }
    }
}

I know I'm missing something fundamental, but I don't know what it is. 我知道我缺少基本的东西,但是我不知道它是什么。 and my googling has been fruitless. 我的谷歌搜索一直没有结果。

There's a MSDN article about ef transactions. 在MSDN上有一篇关于ef交易的文章。

http://msdn.microsoft.com/en-gb/library/vstudio/bb738523(v=vs.100).aspx http://msdn.microsoft.com/zh-CN/library/vstudio/bb738523(v=vs.100).aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM