我的任务是创建一个Blazor ASP.NET Core应用程序,该应用程序将每个表从MS SQL Server数据库导出到它自己的.csv
文件中.我已经将DbContext
个属性中的DbSets
提取到泛型列表中,但是当我try 将泛型对象转换为它们的DbSet
类时,我得到了以下错误:
处理请求时出现未处理的异常. Missing方法异常:类型上的构造函数 ‘Microsoft.EntityFrameworkCore.DbSet`1[[DatabaseTableExport.Data.LoginDbModels.AccountPasswordHistory, 数据库表导出,版本=1.0.0.0,区域性=中性, 找不到PublicKeyToken=NULL]]‘. System.RuntimeType.CreateInstanceImpl(BindingFlags绑定属性,活页夹 活页夹,对象[]参数,文化信息区域性)
我如何修复这个错误,或者有没有更好的方法从DbContext
中提取DbSets
?
using DatabaseTableExport.Data;
using DatabaseTableExport.Data.LoginDbModels;
using Microsoft.AspNetCore.Components;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace DatabaseTableExport.Pages
{
public partial class Index : ComponentBase
{
[Inject]
private LoginDbContext LoginDbContext { get; set; }
[Inject]
private ApplicationDbContext ApplicationDbContext { get; set; }
protected override void OnInitialized()
{
List<DbSet<object>> dbSets = GetDbSets(LoginDbContext);
// iterate through each DbSet instance
foreach (var dbSet in dbSets)
{
// export to csv here
}
}
private static List<DbSet<object>> GetDbSets(DbContext loginDbContext)
{
// Retrieve all the DbSet properties declared on the context class.
var dbSetProperties = loginDbContext.GetType()
.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly)
.Where(p => p.PropertyType.IsGenericType && p.PropertyType.GetGenericTypeDefinition() == typeof(DbSet<>))
.ToList();
// Iterate over each DbSet property and add it to the list of dbsets.
var dbSets = new List<DbSet<object>>();
foreach (var property in dbSetProperties)
{
// If the type of the DbSet is null, skip it.
if (property.PropertyType.GenericTypeArguments.Length <= 0)
{
continue;
}
// Get the generic type arguments and create a corresponding DbSet instance.
var dbsetGenericType = property.PropertyType.GenericTypeArguments[0];
var convertedDbSet = Activator.CreateInstance(typeof(DbSet<>).MakeGenericType(dbsetGenericType), property.GetValue(loginDbContext));
dbSets.Add((DbSet<object>)convertedDbSet);
}
// Return the list of DbSet objects.
return dbSets;
}
}
}