簡體   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