C# 使用实体框架时,分配外键的最佳方式是什么&;LINQ到实体?

C# 使用实体框架时,分配外键的最佳方式是什么&;LINQ到实体?,c#,linq,entity-framework,C#,Linq,Entity Framework,我需要知道创建实体对象和分配外键的最佳实践。这是我的设想。我有一个带有pid、名称、单价等的产品表。。我还有一个带有pid(foregin键)、比率、投票等的评分表。。。目前,我正在执行以下操作以创建评级对象: var prod = entities.Product.First(p => p.product_id == pid); prod.Rating.Load(); if (prod.Rating != null) {

我需要知道创建实体对象和分配外键的最佳实践。这是我的设想。我有一个带有pid、名称、单价等的产品表。。我还有一个带有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();

尽管这样做很好,但我想知道执行此类分配的最佳实践。

每当您总是要加载实体时,只需执行一次往返,并将其包含在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();

每当您总是要加载一个实体时,只需执行一次往返,并将其包含在将由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();