Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 973
Sarah Bailey Avatar asked Mar 22 '15 18:03

Sarah Bailey


People also ask

Do we need EDMX XML file for EF Code First approach?

In code first approach first we create classes (Code) and using this code database will be get generated. We need not use edmx file in code first approach.

Which of the following is the default convention to configure a primary key property in ef6 code first?

Primary Key Convention Code First infers that a property is a primary key if a property on a class is named “ID” (not case sensitive), or the class name followed by "ID". If the type of the primary key property is numeric or GUID it will be configured as an identity column.

How do you call a table valued function in Entity Framework?

Step 1 − Select the Console Application from the middle pane and enter TableValuedFunctionDemo in the name field. Step 2 − In Server explorer right-click on your database. Step 3 − Select New Query and enter the following code in T-SQL editor to add a new table in your database.


1 Answers

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"));
}
like image 148
Sarah Bailey Avatar answered Oct 12 '22 05:10

Sarah Bailey