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?

2
  • You can create a partial class for Samples and add any properties that you want. Commented Jul 2, 2014 at 20:56
  • So how/where would I instantiate that property? Commented Jul 2, 2014 at 21:00

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Alternatively, if you're doing configuration with the Fluent API instead of attributes, you can use the Ignore method.
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 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.
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 Is it ICollection or ICollection<T>? 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<T>() which you can then use OrderBy with. Check here for an answer about casting.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.