Mel*_* NG 3 entity-framework entity-framework-core .net-core asp.net-core
我想创建一个内存中的 SQLite 数据库。
这是startup.cs:
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddDbContext<TestDBContext>().AddEntityFrameworkSqlite();
}
Run Code Online (Sandbox Code Playgroud)
这是数据库的模型:
public class TestModel
{
public string UserName { get; set; }
[Key]
public string id { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
这是数据库的DBContext:
public class TestDBContext : DbContext
{
public virtual DbSet<TestModel> Test { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite("Data Source=:memory:");
}
}
Run Code Online (Sandbox Code Playgroud)
这是控制器:
private readonly TestDBContext TestDBContext;
public HomeController(ILogger<HomeController> logger,TestDBContext _TestDBContext)
{
_logger = logger;
this.TestDBContext = _TestDBContext;
}
public IActionResult Index()
{
TestDBContext.Database.EnsureCreated();
TestDBContext.SaveChanges();
TestDBContext.Test.Add(new TestModel() { User = DateTime.Now.ToString(),id=Guid.NewGuid().ToString() });
TestDBContext.SaveChanges();
return View(TestDBContext.Test.ToList());
}
Run Code Online (Sandbox Code Playgroud)
每次运行都会报错:
Inner Exception 1:
SqliteException: SQLite Error 1: 'no such table: Test'.
Run Code Online (Sandbox Code Playgroud)
我已经使用了EnsureCreated和EnsureCreated运行没有任何错误。为什么还是这个样子?
EF Core 的 DbContext 始终自动打开和关闭与数据库的连接,除非您传递一个已经打开的连接。当连接关闭时,Sqlite 内存数据库将被删除。所以我像这样修改了你的代码。
public void ConfigureServices(IServiceCollection services)
{
var connection = new SqliteConnection("datasource=:memory:");
connection.Open();
services.AddControllersWithViews();
services.AddDbContext<TestDBContext>(options =>
{
options.UseSqlite(connection);
});
}
Run Code Online (Sandbox Code Playgroud)
和数据库上下文类 - 我添加了构造函数,以便我可以提供参数。
public class TestDBContext : DbContext
{
public TestDBContext(DbContextOptions options) : base(options)
{
}
protected TestDBContext()
{
}
public virtual DbSet<TestModel> Test { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
而不是在 Index action 方法中创建数据库,而是在启动时创建它。
| 归档时间: |
|
| 查看次数: |
623 次 |
| 最近记录: |