how to implement computed field for model in web api odata using EF 6

api entity-framework-6 odata web

Question

Everything goes smoothly while I'm building a web api odata controller until I try to add a derived field to the model. The field does not need to be queryable and I do not want it to be present in the database.

provided model

public class Foo
{
    public Int64 Id { get; set; }
    public string SomeDatabaseSourcedField{ get; set; }
    public string SomeDerivedField{ get; set; }
}

If I have a controller, say;

private FooDbContext db = new FooDbContext();

[Queryable]
public IQueryable<Foo> GetFoo()
{        
    return db.Foo;
}

How is the value of set?SomeDerivedField ?

I've attempted to mark the field asnot mapped but it appears that api calls do not return the field.

1
1
7/11/2014 5:44:11 PM

Accepted Answer

Here is my response: I'm using odata version 4. http://aspnet.codeplex.com/SourceControl/latest#Samples/WebApi/OData/v4/ The derived field has been successfully added to the answer.

Create a class that derives from foo first:

public class MyFoo:Foo
{
    public string SomeDerivedField{ get; set; }
}

Create the edm model next:

    public static IEdmModel GetModel()
    {
        ODataConventionModelBuilder builder = new ODataConventionModelBuilder();
        builder.EntitySet<MyFoo>("Foo");
        builder.EntityType<MyFoo>().DerivesFromNothing();

        builder.Namespace = typeof(MyFoo).Namespace;

        return builder.GetEdmModel();
    }

Third, get the information:

    public IHttpActionResult Get()
    {
        IQueryable<MyFoo> foos= db.Foos.Select(
            t => new MyFoo()
            {
                Id = t.Id,
                Name = t.Name,
                SomeDerivedField= t.Name + SqlFunctions.StringConvert((double)t.Id)
            });
        return Ok(foos);
    }
3
7/12/2014 8:19:45 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow