简体   繁体   English

如何在一个控制器/JOIN 中从我的数据库返回/获取两个模型/表或使用存储过程

[英]How to return / GET two models/tables from my DB in one controller / JOIN or use stored procedure

I am trying to create get request that when provided with a broker ID, it returns all the broker information from the Broker table and all of the brokers Applications from the Application table.我正在尝试创建获取请求,当提供代理 ID 时,它会返回代理表中的所有代理信息和应用程序表中的所有代理应用程序。 The two tables are joined by broker ID.这两个表通过代理 ID 连接。

I have tried a few methods found on stakoverflow but keep hitting errors.我尝试了在 stakoverflow 上找到的一些方法,但一直遇到错误。

public class BrokerApplications
    {
        public virtual ICollection<Broker> Broker { get; set; }
        public virtual ICollection<Application> Applications { get; set; }
    }

    

I tried我试过

[HttpGet("{id}")]
        public async Task<ActionResult<BrokerApplications>> GetBrokerApplicationsAsync(int brokerID)
        {
                var brokerApps = (from b in _context.Broker
                                  join a in _context.Application on b.BrokerId equals a.BrokerId
                                  where a.BrokerId == brokerID
                                  //            select new { b.BrokerForename, b.BrokerId, a.RollNumber, a.CustomerFullName }
                                  //).ToList();
                                  select a);
    
                return brokerApps;
}

But got an error message saying但是收到一条错误消息说

"cs0029:cannot implicitly covert type 'System.Linq.IQueryable<SMWEBAPI.Models.Application> to 'Microsoft.AspNetCore.Mvc.ActionResult<SMWebAPI.Controllers.BrokerAppsController.BrokerApplicattions> “cs0029:不能将类型 'System.Linq.IQueryable<SMWEBAPI.Models.Application> 隐式转换为 'Microsoft.AspNetCore.Mvc.ActionResult<SMWebAPI.Controllers.BrokerAppsController.BrokerApplicattions>

This is when I tried这是我尝试的时候

[HttpGet("{id}")] public async Task<ActionResult> GetBrokerApplicationsAsync(int brokerID) { var broker = await _context.Broker.FindAsync(brokerID); [HttpGet("{id}")] public async Task<ActionResult> GetBrokerApplicationsAsync(int brokerID) { var broker = await _context.Broker.FindAsync(brokerID);

            BrokerApplications BrokerApps = new BrokerApplications();

            List<Application> lstApps = new List<Application>();
            lstApps = (List<Application>)_context.Application.Where(a => a.BrokerId == brokerID);
            BrokerApps.Broker = (ICollection<Broker>)broker.ToList();
            BrokerApps.Applications = lstApps;

            return BrokerApps;

} }

but this return the following error message when I tried to call from the URL但是当我尝试从 URL 调用时会返回以下错误消息

InvalidCastException: Unable to cast object of type 'Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable 1[SMWebAPI.Models.Application]' to type 'System.Collections.Generic.List 1[SMWebAPI.Models.Application]'. InvalidCastException:无法将“Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryable 1[SMWebAPI.Models.Application]' to type 'System.Collections.Generic.List对象转换1[SMWebAPI.Models.Application]' to type 'System.Collections.Generic.List 1[SMWebAPI.Models.Application]”。 SMWebAPI.Controllers.BrokerAppsController.GetBrokerApplications(int brokerID) in BrokerAppsController.cs + lstApps = (List)_context.Application.Where(a => a.BrokerId == brokerID); BrokerAppsController.cs 中的 SMWebAPI.Controllers.BrokerAppsController.GetBrokerApplications(int brokerID) + lstApps = (List)_context.Application.Where(a => a.BrokerId == brokerID);

Can someone please help me in how to return from this Get method when provided with a brokerID please?当提供brokerID时,有人可以帮助我如何从这个Get方法返回吗?


UPDATE更新

I haven't been able to return the data as of yet, as when I used a method that didn't give me any errors it returned an empty array.到目前为止,我还无法返回数据,因为当我使用一种没有给我任何错误的方法时,它返回了一个空数组。

[HttpGet("{id}")]
    public async Task<ActionResult<BrokerApplications>> GetBrokerApplicationsAsync(int brokerID)
    {
        return new BrokerApplications()
        {
            Broker = await _context.Broker.Where(x => x.BrokerId == brokerID).ToListAsync(),
            Applications = await _context.Application.Where(a => a.BrokerId == brokerID).ToListAsync()
        };
    }

SO...所以...

I wanted to find another way to get the data.我想找到另一种获取数据的方法。

I have created a stored procedure我创建了一个存储过程

    -- =======================================================
-- Create Stored Procedure Template for Azure SQL Database
-- =======================================================
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author:      <Author, , Name>
-- Create Date: <Create Date, , >
-- Description: <Description, , >
-- =============================================
CREATE PROCEDURE ApplicationsByBroker
(
    -- Add the parameters for the stored procedure here
    @brokerId int
)
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON

    -- Insert statements for procedure here
    SELECT dbo.Application.*, dbo.Broker.*
  FROM dbo.Application, dbo.Broker
WHERE (dbo.Broker.BrokerID = @brokerId AND dbo.Application.BrokerID = 
    @brokerId)

    END
    GO

I ran this to ensure it worked using我运行它以确保它使用

USE SecuredMessagingDatabase;  
GO  
EXEC dbo.ApplicationsByBroker @BrokerId = 1000001;

And I got the expected results, How would I execute this in my web api?我得到了预期的结果,我将如何在我的 web api 中执行它?

It's better to use Include if two objects have a relation by BorkerId , but you can write like this to solve the problem:如果两个对象通过BorkerId有关系,最好使用Include ,但您可以这样写来解决问题:

[HttpGet("{id}")]
public async Task<ActionResult<BrokerApplications>> GetBrokerApplicationsAsync(int brokerID)
{
   return new BrokerApplications()
   {
    Broker = await _context.Broker.Where(x=>x.Id==brokerID).ToListAsync(),
    Applications = await _context.Application.Where(a => a.BrokerId == brokerID).ToListAsync()
   };

  
}

Try the following query, which have one roundtrip to database.试试下面的查询,它有一次到数据库的往返。 I hope EF will not fail.我希望EF不会失败。

class BrokerApplication
{
   public Broker Broker {get; set;)
   public Application Application {get; set;)
}

[HttpGet("{id}")]
public async Task<ActionResult<BrokerApplications>> GetBrokerApplicationsAsync(int brokerID)
{
   var brokers = _context.Broker.Where(x => x.Id == brokerID)
      .Select(b => new BrokerApplication { Broker = b });

   var applications = _context.Application.Where(a => a.BrokerId == brokerID) 
      .Select(a => new BrokerApplication { Application = a });

   var combined = await brokers.Concat(applications).ToListAsync();

   var result = BrokerApplications
   {
     Broker = combined.Where(c => c.Broker != null)
       .Select(c => c.Broker).ToList(),
     Applications = combined.Where(c => c.Application != null)
       .Select(c => c.Application).ToList()
   };
 
   return result;
}

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

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