1

I have 2 tables, one named Products and another named Samples, with a foreign key to a product. A sample simply consist of a decimal value and a timestamp. A product have a name and that's it. But a I want a price (decimal) to be associated with a product. The price should be the latest sample in Samples.

I am interested in using Entity Framework, but how can I achieve a Product Entity with a price value, when it is not directly in the table and some "calculations" need to be performed beforehand?

Peter
  • 505
  • 5
  • 12

1 Answers1

1

There's an attribute called NotMapped that will let you create a property that's, well, not mapped to the database. Doing it code-first, something like this should work:

public class Product
{
    public int Id { get; set; }
    public virtual IEnumerable<Sample> Samples { get; set; }
    [NotMapped]
    public decimal Price
    {
        get { return Samples.OrderByDescending(x => x.TimeStamp).First().Price; }
    }
}

public class Sample
{
    public int Id {get; set;}
    public decimal Price { get; set; }
    [Timestamp]
    public byte[] TimeStamp {get; set;}
}

If it's not code-first, the classes EF builds for you are partial classes, so you can easily extend it similarly.

Pharylon
  • 9,796
  • 3
  • 35
  • 59
  • Alternatively, if you're doing configuration with the Fluent API instead of attributes, you can use the `Ignore` method. – Neil Smith Jul 02 '14 at 21:41
  • But will the queries not be done in memory and not in sql database then? I need great performance because I have a huge set of data, so I cannot neglect performance – Peter Jul 02 '14 at 21:43
  • 2
    @Peter Since `Samples` is marked virtual, it's lazy loaded. So anytime you have a `Product` you will already have its related `Samples`. The `Price` property just returns the most recent Sample from that collection, not the DB. – Neil Smith Jul 02 '14 at 21:45
  • Oh, nice. Do I need to do something different when I do db first? When I try iterating over my products with the [notmapped] prop its way slower than without it. Just makes me nervous – Peter Jul 02 '14 at 21:48
  • Actually when I use db-first my samples are in a ICollection and that interface does not have OrderByDescending? Hmm – Peter Jul 02 '14 at 22:06
  • 1
    @Peter Is it `ICollection` or `ICollection`? I would expect it to be the second which does provide `OrderBy`. If its the first, you can cast it to the generic type by doing `ICollection.Cast()` which you can then use `OrderBy` with. Check [here](http://stackoverflow.com/questions/7757365/does-linq-work-with-ienumerable) for an answer about casting. – Neil Smith Jul 02 '14 at 23:05