简体   繁体   中英

context.Database.EnsureDeleted() and context.Database.EnsureCreated() fails

I try to reproduce this example , it's about testing EF context operations in unit tests (using MS SQL Server). This example contains next code:

using (var context = CreateContext())
{
   context.Database.EnsureDeleted();
   context.Database.EnsureCreated();
...

And it looks ok but ended up with exception:

Cannot open database "EFTestSample" requested by the login. The login failed.

It is very confusing cause EnsureDeleted() should not open any database, it just checks persistence of this one. I'm totally sure it is not security issue, I have tried different cases of login. UPD: EnsureDeleted() works fine (deletes database) when database exists on server.

Any help appreciated, thank.

I've found an answer. It was wrong namespace automatically detected for sample code from example . There are two classes implementing System.Data.Common.DbConnection :

Connection = new Microsoft.Data.SqlClient.SqlConnection(ConnectionString);
Connection = new System.Data.SqlClient.SqlConnection(ConnectionString);

and using the first one is a mistake - exceptions rised by are not captures by EnsureDeleted() method.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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