Val*_*met 2 c# entity-framework-core .net-core
我正在尝试使用Microsoft 文档中的这段代码来实现 EF Core 的单元/集成测试。
但是调用EnsureDeleted()不起作用,会抛出错误
SqlException:用户“sa”登录失败
这是 MS 文档中的示例:
public class SharedDatabaseFixture : IDisposable
{
private static readonly object LockObject = new object();
private static bool isDatabaseInitialized;
public SharedDatabaseFixture()
{
Connection = new SqlConnection("Server =; Database=; User Id=; Password=");
Seed();
Connection.Open();
}
public DbConnection Connection { get; }
public OnlineMenuContext CreateContext(DbTransaction transaction = null)
{
var context = new OnlineMenuContext(
new DbContextOptionsBuilder<OnlineMenuContext>().UseSqlServer(Connection)
.Options
);
if (transaction != null)
{
context.Database.UseTransaction(transaction);
}
return context;
}
private void Seed()
{
lock (LockObject)
{
if (isDatabaseInitialized) return;
using var context = CreateContext();
context.Database.EnsureDeleted(); // Crashes HERE
context.Database.EnsureCreated();
context.Products.Add(DummyData.Product);
context.SaveChanges();
isDatabaseInitialized = true;
}
}
public void Dispose() => Connection.Dispose();
}
Run Code Online (Sandbox Code Playgroud)
我使用了与应用程序中相同的连接字符串,它 100% 有效
EnsureCreated()如果我删除EnsureDeleted()测试按预期运行,则效果很好,但我应该手动删除数据库。
我尝试隔离问题并创建了一个控制台应用程序:
class Program
{
static void Main(string[] args)
{
var connection = new SqlConnection("Perfectly working connection string");
var context = new Context(
new DbContextOptionsBuilder<Context>().UseSqlServer(connection).Options);
// context.Database.EnsureCreated();
context.Database.EnsureDeleted(); // Crashes HERE
}
}
class Context : DbContext
{
public Context(DbContextOptions<Context> options): base(options) { }
private DbSet<Product> Products;
}
class Product
{
public int Id { get; set; }
public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
我正在使用 MacO 来运行这些示例
也许有一些我不知道如何EnsureDeleted运作的东西。
我的问题是:为什么它会抛出此异常,以及如何修复它?
更新:
我使用此处的代码验证了用户 SA 的权限,
SELECT * FROM fn_my_permissions('dbo', 'SCHEMA')
结果如下:
| 归档时间: |
|
| 查看次数: |
2265 次 |
| 最近记录: |