如何在Visual Studio 2012和Entity Framework 5中为单元测试设置LocalDb [英] How to set up LocalDb for unit tests in Visual Studio 2012 and Entity Framework 5

查看:93
本文介绍了如何在Visual Studio 2012和Entity Framework 5中为单元测试设置LocalDb的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个使用Entity Framework 5的Visual Studio 2012 ASP.NET MVC项目.

We have a Visual Studio 2012 ASP.NET MVC project using Entity Framework 5.

有些依赖于数据库的单元测试.在测试项目中设置app.config文件以使用中央SQL Server数据库可以很好地工作.

There are some unit tests that depend on a database. Setting up the app.config file in the test project to use a central SQL Server database works fine.

但是,使用LocalDb会更好,这样每个开发人员在运行测试时都有自己的数据库.尤其是因为我们希望在运行时将测试设置为DropCreateDatabaseAlways.

However, it would be much nicer to use a LocalDb, so that each developer has his/her own database when running the tests. Especially since we would like to have the tests set up to DropCreateDatabaseAlways when running.

但是,我无法进行设置.如果我在app.config中尝试此操作:

However, I can't get the setup to work. If I try this in app.config:

<add name="TestDb" 
   connectionString="Data Source=(LocalDb)\v11.0;Initial Catalog=unittestdb;
     Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\unittestdb.mdf"
   providerName="System.Data.SqlClient" />

我得到:

System.Data.SqlClient.SqlException:发生文件激活错误. 物理文件名"\ unittestdb.mdf"可能不正确.诊断 并更正其他错误,然后重试该操作.创建 数据库失败.列出的某些文件名无法创建.查看 相关错误.

System.Data.SqlClient.SqlException: A file activation error occurred. The physical file name '\unittestdb.mdf' may be incorrect. Diagnose and correct additional errors, and retry the operation. CREATE DATABASE failed. Some file names listed could not be created. Check related errors.

听起来好像它想要mdf文件已经存在,这似乎很奇怪,因为它正在尝试创建数据库.手动创建mdf文件不会更改错误消息.

It sounds like it wants the mdf file to exist already, which seems strange since it is trying to create the database. Creating a mdf file manually does not change the error message.

推荐答案

尝试:

AppDomain.CurrentDomain.SetData(
  "DataDirectory", Path.Combine(AppDomain.CurrentDomain.BaseDirectory, ""));

这将在/bin/Debug/yourdbname.mdf上创建Db文件

This will Create Db File on /bin/Debug/yourdbname.mdf

这篇关于如何在Visual Studio 2012和Entity Framework 5中为单元测试设置LocalDb的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆