Reputation: 13895
I am using Entity Framework for my latest project and my goal is to retrieve the count of the amount of likes a product in the system has.
I have 2 models:
Product and ProductLike
I would like to be able to add an int property to the Product model called NumberOfLikes. However, if I do this EF Migrations will create it as a column in the database. Is there a way to declare a property in a model and then simply get all products and join to get the product like count and set the property?
I am aware this is somewhat what ViewModels are for, but I would like to make the NumberOfLikes property part of the product well before the UI layer, just not part of the database.
Upvotes: 0
Views: 214
Reputation: 554
Try this creating a partial class of the class used in generating your entities and adding the NumberOfLikes property.
public partial class Product
{
public int NumberOfLikes{get; set;}
}
Ensure this class is in the same namespace with your product model class used in generating your database.
With this after loading other properties of your product model, you can populate the NumberOfLikes property and display it.
If you wish to set the value of the NumberOfLikes property everytime you have your product model object, you can do some like this as follows:
public partial class Product
{
int _numberOfLikes;
public int NumberOfLikes{
get{
return _numberOfLikes;
}
set{
_numberOfLikes = this.xxxxx ( the this keyword gives you access to all properties your earlier product model has )
}
}
Note: Setting the NumberOfLikes value from your new partial class might affect performance.
Upvotes: 1