gpt4 book ai didi

c# - 所有实体类型的关键属性必须映射到存储函数返回的相同的不可空列

转载 作者:太空宇宙 更新时间:2023-11-03 23:05:16 28 4
gpt4 key购买 nike

我刚刚创建了一个表值函数,如此处所述 http://www.entityframeworktutorial.net/EntityFramework5/table-valued-function-in-entity-framework5.aspx (使用 EF6)并将其导入我的 edmx。在此之后,我还将 Returns a collection of 更改为我的实体 MyTable(在函数内部选择​​)。

但是,我总是遇到异常

The key properties of all entity types returned by the function import must be mapped to the same non-nullable columns returned by the storage function.

当我查看生成的复杂结果对象时,所有属性都是可空,但在我的实体 MyTable 中,我想映射到它们不是。

这是我的功能(从给定实体获取除实体本身之外的所有子关系):

CREATE FUNCTION [dbo].[fnGetChildren]
(
-- Add the parameters for the function here
@Id uniqueidentifier
)
RETURNS TABLE
AS
RETURN
(
-- Add the SELECT statement with parameter references here
WITH childs AS
(
SELECT * FROM MyTable WHERE Id = @Id
UNION ALL
SELECT MyTable.* FROM MyTable JOIN childs ON MyTable.ParentId = childs.Id
)

SELECT * FROM childs WHERE Id <> @Id
)

该函数在 sql-server 中运行时按预期工作。 edmx-generation也贯穿始终。但是,当尝试使用 DbContext 执行查询时,我得到了这个错误(无论我是否调用函数导入)。

这是函数本身的问题,EF 还是有其他问题?

最佳答案

您可以对 SELECT 列表中的键列使用 ISNULL 以强制 EF 将该值识别为不可为空:

WITH childs  AS
(
SELECT Id FROM MyTable WHERE Id = @Id
UNION ALL
SELECT MyTable.Id FROM MyTable JOIN childs ON MyTable.ParentId = childs.Id
)

SELECT ISNULL(Id, 0) FROM childs WHERE Id <> @Id

您将无法使用 SELECT * 执行此操作,但无论如何您都不应该这样做。

关于c# - 所有实体类型的关键属性必须映射到存储函数返回的相同的不可空列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41462324/

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