Anthony Bobenrieth
Anthony Bobenrieth

Reputation: 2893

Entity Framework Code First: Computed property that can access to is own table

Is it possible to create a computed property in EF code first that can use the others elements of it's own table?

If no, what is the best way to do it without using a context method (i would like a property to bind it on the wpf UI without using converters)?

This example shows what i am trying to do (quietly easy to do in a computed sql field):

class MyEntity{

public virtual decimal Amount { get; set; }

public virtual decimal DivideOfThisAmountOnAll
{
    get
      {
        var sum = *******.sum(e=>e.Amount); //How am i supposed to acces to the others?
        return this.Amount / sum;
      }
 }

}

Upvotes: 0

Views: 1402

Answers (3)

Ackroydd
Ackroydd

Reputation: 1610

I would suggest a navigational property to do this.

class MyEntity{

    public virtual decimal Amount { get; set; }

    public virtual Parent Parent { get; set; }

    public virtual decimal DivideOfThisAmountOnAll
    {
        get
        {
            var sum = Parent.MyEntities.Sum(e=> e.Amount);
            return this.Amount / sum;
        }
    }

}

AaronLS's answer works fine too, but it introduces a dependency on the DbContext (if you care about such things).

Upvotes: 1

AaronLS
AaronLS

Reputation: 38364

You can't do this without accessing the db context. You could come up with some scheme where you inject it into the entity, etc. but basically you would query the db context just as you would with any other query.

class MyEntity{
  public virtual decimal Amount { get; set; }

  public virtual decimal DivideOfThisAmountOnAll(YourDbContext db)
  {  
        var sum = db.LinqQueryHereToAggregateAsYouPlease.Single();
        return this.Amount / sum;
  }

}

Upvotes: 1

Godeke
Godeke

Reputation: 16281

Instead of directly modifying your database object, I would recommend making a business logic layer for binding. Tools like https://github.com/AutoMapper/AutoMapper make it easy to transfer most of your table entities across without modification and then do things like create summary values, complex computed fields and other non-stored data tasks.

In MVC this is called Model, View, ViewModel, Controller, where the ViewModel is what you bind to and has all the computed results.

This does introduce additional complexity, but it leaves your Model objects alone (which is a good thing) and allows you to isolate your rules to one location (the ViewModel) which can avoid spreading the same computations across many controllers (which is an anti-pattern).

Upvotes: 2

Related Questions