gpt4 book ai didi

c# - 如何使用 FromSqlRaw Entity Framework Core 3.1 从存储过程返回多个 SELECT 集

转载 作者:行者123 更新时间:2023-12-04 07:27:09 30 4
gpt4 key购买 nike

我目前从数据库返回值时遇到问题,我正在使用 SQL Server 存储过程和 ASP.NET Core 3.1 来检索多个 SELECT 集。

这是我的存储过程:

ALTER PROCEDURE [dbo].[MyProc]
@BusinessModelID int
AS
BEGIN
SELECT Id, Title
FROM [dbo].[Channels]
WHERE BusinessModelId = @BusinessModelID;

SELECT Id, Title
FROM [dbo].[Problems]
WHERE BusinessModelId = @BusinessModelID;

SELECT Id, Title
FROM [dbo].[CostStructures]
WHERE BusinessModelId = @BusinessModelID;

SELECT Id, Title
FROM [dbo].[CustomerSegments]
WHERE BusinessModelId = @BusinessModelID;

SELECT Id, Title
FROM [dbo].[KeyMetrics]
WHERE BusinessModelId = @BusinessModelID;

SELECT Id, Title
FROM [dbo].[RevenueStreams]
WHERE BusinessModelId = @BusinessModelID;

SELECT Id, Title
FROM [dbo].[Solutions]
WHERE BusinessModelId = @BusinessModelID;

SELECT Id, Title
FROM [dbo].[Unfairs]
WHERE BusinessModelId = @BusinessModelID;

SELECT Id, Title
FROM [dbo].[Values]
WHERE BusinessModelId = @BusinessModelID;
END

这是我的 C# 代码:

var modelList = _dataContext.Set<BusinessToGet>()
.FromSqlRaw($"EXECUTE MyProc @BusinessModelID={businessModelId}")
.ToList();

问题是它应该返回多个集合,但它只返回一个 channel 。我做错了什么?

提前致谢。

最佳答案

更新

在这种情况下,表中存在重复的主键。尽管下面的 SQL 在 SQL-server 中运行良好,但 EF Core 返回了很多重复的实例,因为当 EF Core 看到一个 Id = 1 的实例时,它会将它用于所有 Id = 1 的后续实例。

解决方法是对 FromSqlRaw 查询使用无 key DTO。

[Keyless]
public class BlogPostsCount
{
Id,
public int Id { get; set; }
public string Title { get; set; }
}

https://learn.microsoft.com/en-us/ef/core/modeling/keyless-entity-types?tabs=data-annotations


使用 UNION 应该可以解决这个问题。如果表之间的数据类型不同,您可能还需要强制转换列值才能获得统一的结果。如果您在多个表中有重复项,并且需要全部,请使用 UNION ALL

SELECT Id, Title FROM [dbo].[Channels] WHERE BusinessModelId = @BusinessModelID
UNION
SELECT Id,Title FROM [dbo].[Problems] WHERE BusinessModelId = @BusinessModelID
UNION
SELECT Id, Title FROM [dbo].[CostStructures] WHERE BusinessModelId = @BusinessModelID
UNION
SELECT Id, Title FROM [dbo].[CustomerSegments] WHERE BusinessModelId = @BusinessModelID
UNION
SELECT Id, Title FROM [dbo].[KeyMetrics] WHERE BusinessModelId = @BusinessModelID
UNION
SELECT Id, Title FROM [dbo].[RevenueStreams] WHERE BusinessModelId = @BusinessModelID
UNION
SELECT Id, Title FROM [dbo].[Solutions] WHERE BusinessModelId = @BusinessModelID
UNION
SELECT Id, Title FROM [dbo].[Unfairs] WHERE BusinessModelId = @BusinessModelID
UNION
SELECT Id, Title FROM [dbo].[Values] WHERE BusinessModelId = @BusinessModelID

关于c# - 如何使用 FromSqlRaw Entity Framework Core 3.1 从存储过程返回多个 SELECT 集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68153841/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com