【问题标题】:How to bind Product and Item in Entity Framework?如何在实体框架中绑定产品和项目?
【发布时间】:2011-10-12 07:21:27
【问题描述】:

我已经绑定到类中,但没有绑定到另一个类中。我无法从 Item 中调用 Product:对象引用未设置为对象的实例。

怎么了?

如何优化这段代码?

foreach (var xd in excelData)
{
    Product p = new Product { 
        Name = xd.ProductName,
    };

    ctx.Products.Add(p);
    ctx.SaveChanges();

    Item t = new Item { 
        Product=p,
    };

    t.ProductId = t.Product.ProductId;
    ctx.Items.Add(t);
    ctx.SaveChanges();

    t.Product = ctx.Products.Where(c => c.ProductId == t.ProductId).FirstOrDefault();
    ctx.SaveChanges();
}

【问题讨论】:

    标签: linq entity-framework linq-to-entities entity-framework-4.1


    【解决方案1】:

    假设你的ProducId和ItemIdare auto generated you can write this with a single call toSaveChanges`如下

    foreach (var xd in excelData)
    {
        Product p = new Product { 
            Name = xd.ProductName,
        };
    
        Item t = new Item { 
            Product=p,
        };
    
        ctx.Items.Add(t);    
    }
    
    ctx.SaveChanges();
    

    【讨论】:

      【解决方案2】:

      ObjectQuery.Include 方法。指定要包含在查询结果中的相关对象。

      ctx.Items.Include("Product").Where(c => c.SupplierId == id).ToList().ForEach(t =>
              {
                  li.Add(new ShortPricesListItem()
                  {
                      Name = t.Product.Name,
                  });
              });
      

      【讨论】:

        猜你喜欢
        • 2018-05-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-06-21
        • 2011-12-05
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多