【问题标题】:What is the best way in assigning foreign key when using entity framework & LINQ to Entities?使用实体框架和 LINQ to Entities 时分配外键的最佳方法是什么?
【发布时间】:2015-09-08 11:38:41
【问题描述】:

我需要知道创建实体对象和分配外键的最佳实践。这是我的场景。我有一个带有 pid、name、unit_price 等的 Product 表。我还有一个带有 pid(外键)、rate、votes 等的 Rating 表……目前我正在执行以下操作来创建 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();

尽管这很好用,但我想知道执行此类作业的最佳做法。

【问题讨论】:

    标签: c# linq entity-framework


    【解决方案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();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-10
      • 1970-01-01
      • 2011-12-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多