我通过EF core访问我的cosmos db数据库。
我通过Ef core重写了OnModelCreating来检查底层数据库和容器是否存在。但是我不确定我应该如何检查它是否包含任何数据?
EfCore似乎没有任何计数,或者没有办法检查底层db是否为空?
这是我到目前为止所尝试的
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
var client = Database.GetCosmosClient();
var dbResponse = client.CreateDatabaseIfNotExistsAsync("Db").Result.StatusCode;
ContainerProperties containerProperties = new ContainerProperties("forms", "/forms");
var database = client.GetDatabase("Db");
var containerResponse = database.CreateContainerIfNotExistsAsync(containerProperties).Result.StatusCode;
//Database or container was recently created, hence reseed
if (dbResponse == System.Net.HttpStatusCode.Created
|| containerResponse == System.Net.HttpStatusCode.Created)
{
Console.WriteLine("Model created but need seeding");
return;
}
var container = database.GetContainer("forms");
//How to check data is in the container?
}
根据@Svyatoslav Danyli提供的答案,我创建了两个方法。
using Microsoft.EntityFrameworkCore;
using System.Linq;
namespace FormsRetriever
{
public static class SeedingTools
{
public static void CheckDatabase(DbContext dbContext)
{
dbContext.Database.EnsureCreated();
var client = dbContext.Database.GetCosmosClient();
SeedData(dbContext);
}
private static void SeedData(DbContext dbContext)
{
bool a = dbContext.Set<Forms>().Any();
}
}
}
我在启动时调用。
返回给我这个错误
A host error has occurred during startup operation '50913447-b407-41a1-95bd-68918f9d3d4b'.
[2022-07-04T11:04:53.059Z] Microsoft.EntityFrameworkCore: The LINQ expression 'DbSet<Forms>()
[2022-07-04T11:04:53.059Z] .Any()' could not be translated. Either rewrite the query in a form that can be translated, or switch to client evaluation explicitly by inserting a call to 'AsEnumerable', 'AsAsyncEnumerable', 'ToList', or 'ToListAsync'. See https://go.microsoft.com/fwlink/?linkid=2101038 for more information.
将检查代码移动到适当的函数中,并在EF Core正确配置时执行:
public static class DatabaseTools
{
public static void CheckDatabase(DbContext context)
{
// EF Core will create database and containters
context.Database.EnsureCreated();
// Cosmos provider do not supports Any
if (dbContext.Set<Form>().FirstOrDefault() == null)
{
// seed data
context.Set<Form>().AddRange(
new []
{
new Form{},
new Form{},
new Form{},
}
);
context.SaveChanges();
}
}
}