【问题标题】:Is there any way that could help me select specific data from table in Microsoft.AspNetCore.Datasync.EFCore有什么方法可以帮助我从 Microsoft.AspNetCore.Datasync.EFCore 中的表中选择特定数据
【发布时间】:2022-11-16 02:57:14
【问题描述】:

我正在了解从 API 到 WPF 应用程序的数据同步。从https://github.com/Azure/azure-mobile-apps/tree/main/samples 得到了一个演示。但是我遇到了一个问题,即表中的所有数据都是在调用时收集的,但我需要使用 Id 选择特定数据。尝试查询等都一无所获。请指导我 谢谢

PatientsController.cs

[Route("tables/Patients")]
public class PatientsController : TableController<Patients>
{
    public PatientsController(AppDbContext context)
        : base(new EntityTableRepository<Patients>(context))
    {

    }
}

AppDbContext.cs

public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
    {
    }
    public DbSet<Patients> Patients => Set<Patients>();
}

【问题讨论】:

  • context.Patients.FirstOrDefault(x =&gt; x.Id == 1) 应该给你一个特定的 Patients 对象,如果这是你想要的(假设 Patients 有一个 Id 属性)
  • @mm8 感谢回复。我已经试过那个方法了。 EntityTableRepository<Patients>(context) 参数只接受 dbcontext 对象。当我这样过滤时,会弹出一个错误“无法从‘System.Linq.IQueryable<TestApp.Api.Models.Patients>’转换为‘Microsoft.EntityFrameworkCore.DbContext’”。
  • 为什么要进行这种转换以及在哪里进行?您在哪里以及如何尝试过滤数据?

标签: wpf asp.net-core-webapi azure-mobile-services


【解决方案1】:

尝试使用以下代码:

public class AppDbContext : DbContext
{
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
    {
    }
    public DbSet<Patients> Patients {get;set;}
}

控制器:

[Route("tables/Patients")]
public class PatientsController : TableController<Patients>
{
    private readonly AppDbContext _context;
    public PatientsController(AppDbContext context)
        : base(new EntityTableRepository<Patients>(context))
    {
        _context=context;
    }
    public async Task<IActionResult> Index(int id){
         var Patients=_context.Patients.FindAsync(id);
         return View(Patients);
    }
}

【讨论】:

  • 谢谢。 [HttpGet("{id}/patientlist")]public ActionResult&lt;Patients&gt; Index(Int64 id){ var PatientsList = _context.Patients.Where(x =&gt; x.ClinicId == id).ToList();return Ok(PatientsList);}。当我这样做时,我得到了预期的回应,谢谢你的想法。
  • 但是遇到一个新问题,比如我打电话给localhost:7178/tables/Patients/0002/…,我只能从那个诊所得到病人的回应。但是当我在我的 WPF 应用程序中调用它时 _client = new DatasyncClient("localhost:7178/tables/Patients/0002/…", options); _table = _client.GetRemoteTable<患者>();表中的所有患者都放在一起。
  • 你能分享你的动作吗?并检查你在调试时是否每次都在你的动作中获得id?
【解决方案2】:

如果您只需要通过 Id 获取记录,您可以使用 URL https://mysite/tables/myTable/id - 无需搜索 - 它会直接转到您想要的实体。

如果您需要限制用户可以看到的内容,则需要实施访问控制提供程序(这是 IAccessControlProvider 的实施)。这提供了三种方法来限制用户可以看到的内容并进行模型更新以确保写入操作存储正确的内容。你可以在这里阅读更多:https://learn.microsoft.com/en-us/azure/developer/mobile-apps/azure-mobile-apps/howto/server/dotnet-core#configure-access-permissions

如果是别的,你需要更具体一点。我经常参与 azure/azure-mobile-apps 存储库的问题和讨论,所以请随时在那里提出问题。

【讨论】:

    猜你喜欢
    • 2021-03-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-24
    • 2012-06-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多