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?
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.