结果集缺少主键的存储过程不会以 Entity Framework 6 执行

Stored procedure whose result set lacks a primary key won't execute with Entity Framework 6

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

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

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

我尝试在 EF 中为 Foo 定义一个主键,但是这个值从未从存储过程中得到 returned,所以我得到了这种错误:

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.

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

我不确定如何才能 Entity Framework 帮助我执行存储过程和 return 正确的结果。


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

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 没有相应的数据库 table,并且无法创建数据库,这可能存在问题。相反,我为 Foo.

添加了一个新的复杂类型

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

最后,存储过程 GetFoo() 能够被修改为 return 单个谓词 table 结果集(第一个 SP returned 两个明确的结果集之一不同的结果集,取决于 if 语句的结果)。作为一些额外的预防措施,我确保每个结果记录都有一个唯一的 GUID 用作键(尽管我无法为其相应的复杂类型定义键),并且我为 SP return 的每一列添加了别名编辑

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