gpt4 book ai didi

c# - 结果集缺少主键的存储过程将无法使用 Entity Framework 6 执行

转载 作者:行者123 更新时间:2023-11-30 17:44:40 27 4
gpt4 key购买 nike

我正在调用一个存储过程,其结果集没有主键,也没有候选键。我创建了一个名为 Foo 的实体表示结果集中的记录,因此存储过程将产生 List<Foo> .该实体看起来像这样:

public class Foo {
public Guid FooID { get; set; }
public Guid AnotherFooID { get; set; }
public string FooString { get; set; }
}

当我尝试按原样调用存储过程时,它会导致编译错误,因为 Foo没有定义主键。

我尝试为 Foo 定义主键在 EF 中,但是这个值永远不会从存储过程中返回,所以我得到了这种错误:

The data reader is incompatible with the specified 'Database.Foo'. A member of the type, 'FooPrimaryKey', does not have a corresponding column in the data reader with the same name.

我无法修改存储过程以返回一个“唯一”列(这可能允许我创建一个实体并将该列定义为主键)。此外, Entity Framework 不允许我设置导入函数 to return a complex type , 因为 if()存储过程返回语句中的子句。

我不确定如何让 Entity Framework 帮助我执行存储过程并返回正确的结果。


编辑:我决定将实体中的每一列定义为一个大复合键。然后调用存储过程(像这样)返回正确的结果集:

var fooList = db.GetFoo(param1, param2); // etc.

但稍后,如果我再次查询数据库(在本例中,使用 LINQ),则会抛出错误:

An exception of type 'System.Data.Entity.Core.EntityCommandCompilationException' occurred in EntityFramework.SqlServer.dll but was not handled in user code. An error occurred while preparing the command definition.

最佳答案

问题是通过以下方式解决的:

Foo 被定义为实体而非复杂类型。可能存在问题,因为 Foo 没有相应的数据库表,也无法创建。相反,我为 Foo 添加了一个新的复杂类型。

接下来,我为后续的 LINQ 查询创建了第二个 using() block 。

最后,存储过程 GetFoo() 可以修改为返回一个可预测的结果集(第一个 SP 返回两个完全不同的结果集之一,取决于 的结果code>if 语句)。作为一些额外的预防措施,我确保每个结果记录都有一个唯一的 GUID 用作键(尽管我无法为其相应的复杂类型定义键),并且我为 SP 返回的每一列添加了别名。

我无法确定这些措施中的哪一个解决了我的问题,但我希望这对遇到类似问题的人有用。

关于c# - 结果集缺少主键的存储过程将无法使用 Entity Framework 6 执行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29172885/

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