c# - 将 EF6 存储函数用于 Entity Framework 代码优先,我可以返回自定义类型吗?

标签 c# entity-framework ef-code-first

我有一个实体类:

public class SomeClass {
    public int Id { get; set; }
    public int Value { get; set; }
    public string Name { get; set; }
}

使用 EF6 Store Functions for Entity Framework code-first通过 Moozzyk,我看到了将函数映射到实体类型的示例代码。

但是,当使用尚未映射为实体的类型时,我收到一个异常,指出该类型不是有效的实体类型。

例子:

[DbFunction("MyContext", "GetValueSum")]
public IQueryable<SomeClassSummary> GetValueSum()
{
    return ((IObjectContextAdapter)this).ObjectContext
            .CreateQuery<SomeClassSummary>(string.Format("[{0}].{1}", GetType().Name,
            "[GetValueSum]()"));
}

如何将该函数的调用输出到特定类型?

最佳答案

要返回的类型必须具有与函数同名的列。例如,如果函数返回列:

Name nvarchar
Sum  int

那么 SomeClassSummary 应该是:

public class SomeClassSummary {
    public string Name { get; set; }
    public int Sum { get; set; }
}

然后在上下文中,将类添加为复杂类型:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.ComplexType<SomeClassSummary>();
    modelBuilder.Conventions.Add(new FunctionsConvention<MyContext>("dbo"));
}

关于c# - 将 EF6 存储函数用于 Entity Framework 代码优先,我可以返回自定义类型吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29198416/

相关文章:

C# Express 2010 多线程

c# - 如何解决 C# .NET N 层应用程序中的乐观并发更新?

entity-framework - EF 代码第一个 : Fluent API Configuration - How to configure properties of subclasses in TPH?

c# - 如何在 EF 4.1 RC 中的 DbContext 级别关闭更改跟踪?

entity-framework - EntityFramework数据初始化

c# - Linq to Entities 过滤器导航集合属性

c# - 从模板生成 PDF 的最佳方式

c# - MVC 3 级联下拉列表

c# - 使用 WPF 和 MySql 在 EF 6.0 中过滤实体

entity-framework - Entity Framework 花费大量时间初始化模型