实体框架,一对多,几列

时间:2012-07-02 13:51:49

标签: entity-framework

如果我有一个主表,让我们说订单,一个子表项和items表有一个项目编号字段BUT它还有一个可以为颜色的可空(可选)字段,仅适用于某些项目。如何使用Entity Framework?

更新orders表,同时更新orders表

这是我到目前为止的代码示例。两个问题,我只是输入了我的一个项目,从我的研究表明,我不能在项目表中添加另一个字段?

    foreach (Guid c in AllItems)
    { Items.OrderItemID = Guid.NewGuid();
      ITemsOrderID = order.OrderID;
      ITems.ItemID = c;
      If (ItemID = ItemThatLetsYouChoseAColorID)
      {
          Items.ItemColorID = ColorID;
      } else {
          Items.ItemColorID = null;
      }
     }
     context.Orders.AddObject(Orders);
     context.Items.AddObject(Items);
     context.SaveChanges();

我的订单表会插入一条记录,并且Items会插入一条记录。我很遗憾这里缺少一些基本的东西。顺便说一下,这是Entity Framework 4.0,它。我相信,不需要使用EntityKey。

2 个答案:

答案 0 :(得分:1)

您只是在Items范围之后的foreach集合中添加了一个对象。

你测试过类似的东西吗?

foreach (Guid c in AllItems)
{
    var Item = new Item();

    Item.OrderItemID = Guid.NewGuid();
    Item.OrderID = order.OrderID;
    Item.ItemID = c;
    If (ItemID = ItemThatLetsYouChoseAColorID)
    {
        Item.ItemColorID = ColorID;
    }
    else
    {
        Item.ItemColorID = null;
    }

    context.Items.AddObject(Items);
}

context.Orders.AddObject(order);
context.SaveChanges();

而且我不确定你理解你的意思

  

我无法在items表中添加另一个字段

你应该更准确地了解你的期望。插入一行,在表格中添加一列......?什么是“领域”?

答案 1 :(得分:0)

这是工作代码。我在foreach项循环之外有了新项,所以覆盖了这个值。另外,我需要将每个添加到上下文中。我很难用这个,希望它可以帮助别人:

    <-fill the order object->
    foreach (Guid i in Items)
    {
        **Items item = new Items();**
        item.ItemID = Guid.NewGuid();
        item.OrderID = order.OrderID;
        if (i == ItemWithColorGuid)
        {
            foreach (Guid c in Colors)
            {
                **Items color = new Items();**
                color.ItemsID = Guid.NewGuid();
                color.OrderID = order.orderID;
                color.itemID = g;
                color.colorID = c;
                context.item.AddObject(color);
            }
        }
        else
        {
            item.ItemID = i;
            item.ColorID = null; 
            context.item.AddObject(item);
        }                        
    }
    context.orders.AddObject(order);
    context.SaveChanges();