繁体   English   中英

是否可以将 DbSet 与泛型类型一起使用?

[英]Is it possible to use the DbSet with a generic type?

我一直在为康复中心搭建一个平台。 我们需要存储约会信息,每个约会都有多个考勤 forms ,每个考勤表格是数据库中的一个表。 所以,我有Appointments表和每个出席表格的一个表。 我需要恢复某个约会的数据以及该特定约会中使用的所有出勤 forms。 问题是每次预约的出勤人数 forms 各不相同,因为医疗保健专业人员可以根据预约填写不同的出勤人数 forms 。

所有考勤名称 forms 都有相同的前缀,所以我可以这样做:

var formsNamesQuery = from table in _context.GetType().GetProperties()
                      where table.Name.StartsWith("Form") 
                      select table.Name;

var formsNames = formsNamesQuery.ToList();

这样做,现在我只有出勤表的名称。 要查询每个表,我这样做:

foreach (var formName in formsNames)
{
     var form = _context.GetType().GetProperty(formName).GetType();
     
     var formResults = _context.Set<FormType>().FromSqlRaw(
          $"SELECT * FROM {formName} WHERE PacientID = '{pacientID}' AND AppointmentID = {appointmentID}")
          .AsNoTracking()
          .FirstAsync();
}

但我不知道如何向DbContext说我正在搜索的表单的类型。 我一直在寻找很多,但我没有找到解决方案。 我看到了这个问题,它使我采用了这种方法

public IList RestoreFormInfo<TEntity>(TEntity entity, string formName, string pacientID, int AppointmentID) where TEntity : class
{
     var dataSet = _context.Set<TEntity>();

     var results = dataSet.FromSqlRaw(
          $"SELECT * FROM {formName} WHERE PacientID = '{pacientID}' AND AppointmentID = {appointmentID}")
          .AsNoTracking()
          .FirstAsync();
     
     return (IList) results;
}

我这样称呼它:

var formResults = RestoreFormInfo(form.GetType(), formName, pacientID, appointmentID);

使用此方法,我可以传递表单类型,但出现此错误

InvalidOperationException: Cannot create a DbSet for 'Type' because this type is not included in the model for the context.
Microsoft.EntityFrameworkCore.Internal.InternalDbSet<TEntity>.get_EntityType()
Microsoft.EntityFrameworkCore.Internal.InternalDbSet<TEntity>.CheckState()
Microsoft.EntityFrameworkCore.Internal.InternalDbSet<TEntity>.get_EntityQueryable()
Microsoft.EntityFrameworkCore.Internal.InternalDbSet<TEntity>.System.Linq.IQueryable.get_Provider()
Microsoft.EntityFrameworkCore.RelationalQueryableExtensions.FromSqlRaw<TEntity>(DbSet<TEntity> source, string sql, object[] parameters)
SigCER.Controllers.AppointmentsController.RestoreFormInfo<TEntity>(TEntity entity, string formName, string pacientID, int appointmentID) in AppointmentsController.cs
var results = dataSet.FromSqlRaw(
SigCER.Controllers.AppointmentsController.AttendanceForms(int appointmentID, string pacientID) in AppointmentsController.cs
var formResults = RestoreFormInfo(form.GetType(), formName, pacientID, appointmentID);
lambda_method(Closure , object )
Microsoft.Extensions.Internal.ObjectMethodExecutorAwaitable+Awaiter.GetResult()
Microsoft.AspNetCore.Mvc.Infrastructure.ActionMethodExecutor+TaskOfActionResultExecutor.Execute(IActionResultTypeMapper mapper, ObjectMethodExecutor executor, object controller, object[] arguments)
System.Threading.Tasks.ValueTask<TResult>.get_Result()
System.Runtime.CompilerServices.ValueTaskAwaiter<TResult>.GetResult()
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeActionMethodAsync>g__Awaited|12_0(ControllerActionInvoker invoker, ValueTask<IActionResult> actionResultValueTask)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeNextActionFilterAsync>g__Awaited|10_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Rethrow(ActionExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(ref State next, ref Scope scope, ref object state, ref bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, object state, bool isCompleted)
Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Authentication.AuthenticationMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.MigrationsEndPointMiddleware.Invoke(HttpContext context)
Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.Diagnostics.EntityFrameworkCore.DatabaseErrorPageMiddleware.Invoke(HttpContext httpContext)
Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

我必须像这样解决问题:

foreach (var formName in formsNames)
{
     var form = typeof(DbContext).GetProperty(formName).PropertyType;
     
     var method = typeof(AppointmentsController).GetMethod("RestoreFormInfo");

     // Because the form variable is a DbSet<FormType>, I needed to get the
     // FormType from the GenericTypeArguments array.
     var genericMethod = method.MakeGenericMethod(form.GenericTypeArguments[0]);

     var formResults = await (Task<object>) genericMethod.Invoke(this, new object[] { formName, pacientID, appointmentID });
}

现在, RestoreFormInfo方法是这样的:

public async Task<object> RestoreFormInfo<TEntity>(string formName, string pacientID, int AppointmentID) where TEntity : class
{
     var dataSet = _context.Set<TEntity>();
     
     try
     {
          var results = await dataSet.FromSqlRaw(
               $"SELECT * FROM {formName} WHERE PacientID = '{pacientID}' AND AppointmentID = {appointmentID}")
               .AsNoTracking()
               .FirstAsync();
     }
     catch (InvalidOperationException)
     {
          // The expected error is the "InvalidOperationException: Enumerator failed to MoveNextAsync",
          // it means that the FirstAsync didn't find any result.
          return null;
     }
     
     return results;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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