Using EF6 Store Functions for Entity Framework code-first, can I return a custom type?

送分小仙女□ 提交于 2019-12-13 12:09:14

问题


I have an entity class:

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

using the EF6 Store Functions for Entity Framework code-first by Moozzyk, I see example code that maps a function to an entity type.

However, when using a type that isn't already mapped as an entity, I receive an exception saying the type is not a valid entity type.

Example:

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

How can I output the call of that function to a specific type?


回答1:


The type to be returned must have columns named the same as the function. For example, if the function returns columns:

Name nvarchar
Sum  int

then SomeClassSummary should be:

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

Then in the context, add the class as a complex type:

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


来源:https://stackoverflow.com/questions/29198416/using-ef6-store-functions-for-entity-framework-code-first-can-i-return-a-custom

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!