简体   繁体   中英

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

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?

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"));
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM