質問

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

}
役に立ちましたか?

解決

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).

他のヒント

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

}

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).

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top