我正在通过 COM 在 C++ 非托管解决方案中实现 C# 项目。C# 项目使用 EntityFramework 来返回有关数据库的值。
当我们在此解决方案中从 UnitTest C# 项目中调用“Test()”方法时,一切正常。当我们从非托管 C++ 调用它时,在调用的“Test()”方法中会发生异常。
例外:
No connection string named 'Entities' could be found in the application
config file.
我们在非托管 C++ 中调用“Test()”方法的位置:
AServer::Server_InterfacePtr p(__uuidof(AServer::Server));
long res = p->Test(); // gives 1337, WRONG: it should give the count of users
C#项目中被调用的方法:
public int Test()
{
TextWriterTraceListener myTextListener = new TextWriterTraceListener(@"C:\log.txt");
Trace.Listeners.Add(myTextListener);
try
{
Entities model = new Entities();
ObjectResult<UserGetAll_Result> res = model.UserGetAll();
return res.Count;
}
catch (Exception e)
{
Trace.WriteLine(e.Message); // writes out "No connection string named 'Entities' could be found in the application config file."
return 1337;
}
}
单元测试方法:
[TestMethod]
public void TestMethod1()
{
Server server = new Server();
var res = server.Test(); // OK: gives the count of users
}
无论如何我们可以解决这个问题吗?我们曾考虑在“Test()”方法中将 ConnectionString 作为参数提供给模型的构造函数,但显然Entities
不接受 ConnectionString 作为其构造函数中的参数。
连接字符串已在App.Config
. AntiityFramework使用的版本是5,解决方案针对frameworkversion 4.0。
不使用 EntityFramework 的方法工作得很好。