我需要知道创建实体对象和分配外键的最佳实践。这是我的情景。我有一个带有pid,name,unit_price等的Product表。我还有一个带有pid(foregin密钥),评级,投票等的评级表...目前我正在做以下创建评级对象:
var prod = entities.Product.First(p => p.product_id == pid);
prod.Rating.Load();
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();
尽管这很好用,但我想知道做这些作业的最佳做法。
答案 0 :(得分:1)
每当您总是要加载实体时,只需进行一次往返,并将其包含在将由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();