![](/img/trans.png)
[英]Best way to link a list of foreign keys to a list of entities in entity framework
[英]What is the best way in assigning foreign key when using entity framework & LINQ to Entities?
我需要了解创建实体对象和分配外键的最佳实践。 这是我的情况。 我有一个带有pid,名称,单价等的Product表。我也有一个带有pid(外键),rate,votes等的Rating表。目前,我正在执行以下操作来创建评价对象:
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();
即使此方法工作正常,我仍想了解进行此类分配的最佳实践。
每当您总是要加载一个实体时,只需进行一次往返,并将其包含在将由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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.