我创建了一个包含单元项目的 Asp.net Telerik MVC 4 应用程序。当我尝试在单元测试中初始化用户对象时,它失败了。它给出了一条错误消息,指出配置文件中不存在连接字符串。但是,我检查了配置文件,并且连接字符串在那里。
以下是一些示例代码:
//连接字符串
<connectionStrings>
<add name="KMSSEntities" connectionString="metadata=res://*/Models.KMSSEntityModel.csdl|res://*/Models.KMSSEntityModel.ssdl|res://*/Models.KMSSEntityModel.msl;provider=System.Data.SqlClient;provider connection string="data source=(local);initial catalog=KMSS;persist security info=True;user id=******;password=*******;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
//Initialize my Context
private KMSSEntities entity = new KMSSEntities();
//This is my insert user
public void InsertUser(User user)
{
entity.Users.Add(user);
}
//this is code in the test method
User u = new User();
u.UserName = "test";
u.password = "Password";
u.FirstName = "first";
u.LastName = "Last";
StudentRepository rep = new StudentRepository(new KMSSEntities());
rep.InsertUser(u); **//This is where it's returning the error message**
rep.Save();
//这是堆栈跟踪。
at System.Data.Entity.Internal.LazyInternalConnection.get_ConnectionHasModel()
at System.Data.Entity.Internal.LazyInternalContext.InitializeContext()
at System.Data.Entity.Internal.InternalContext.Initialize()
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
at System.Data.Entity.Internal.Linq.InternalSet`1.Initialize()
at System.Data.Entity.Internal.Linq.InternalSet`1.get_InternalContext()
at System.Data.Entity.Internal.Linq.InternalSet`1.ActOnSet(Action action, EntityState newState, Object entity, String methodName)
at System.Data.Entity.Internal.Linq.InternalSet`1.Add(Object entity)
at System.Data.Entity.DbSet`1.Add(TEntity entity)
at KMSS.Models.UserRepository.InsertUser(User user) in c:\com\KMSS\KMSS\KMSS\Models\UserRepository.cs:line 29
at KMSSTests.UnitTest1.TestMethod1() in c:\com\KMSS\KMSS\KMSSTests\UnitTest1.cs:line 21