What is the best way in assigning foreign key when using entity framework & LINQ to Entities?
I need to know the best practice of creating an entity object and assigning the foreign key. Here is my scenario. I have a Product table with pid,name,unit_price etc.. I also have a Rating table with pid (foregin key),rate,votes etc... Currently i am doing the following to create the rating object:
var prod = entities.Product.First(p => p.product_id == pid);
prod.Rating.Load();
if (prod.Ratin开发者_运维问答g != null)
{
log.Info("Rating already exists!");
// set values and Calcuate the score
}
else
{
log.Info("New Rating!!!");
Rating rating = new Rating();
// set values and do inital calculation
prod.Rating = rating;
} entities.SaveChanges();
Even though this works fine, I would like to know the best practice in doing these kind of assignment.
Whenever you are always going to load an entity, just do one round trip, and include it in the query that will get generated by EF.
Product prod = entities
.Product.Include("Rating")
.First(p => p.product_id == pid);
if (prod.Rating != null)
{
log.Info("Rating already exists!");
// set values and Calcuate the score
}
else
{
log.Info("New Rating!!!");
Rating rating = new Rating();
// set values and do inital calculation
prod.Rating = rating;
}
entities.SaveChanges();
精彩评论