代码之家  ›  专栏  ›  技术社区  ›  Binoj Antony

实体框架中主细节/多表插入的最佳实践/方法

  •  7
  • Binoj Antony  · 技术社区  · 16 年前

    我的桌子结构是这样的

    Orders
    ------ 
    Id int identity
    OrderDate smalldatetime
    OrderStatusid tinyint
    
    Products
    --------
    Id int identity
    Name varchar(50)
    
    OrderDetails
    ------------
    Id int identity
    OrderId int (fkey)
    ProductId int (fkey)
    Amount decimal
    Rate decimal
    

    我正在尝试使用下面的代码使用实体框架执行插入操作
    这是插入的最佳方法吗?
    我对从上下文对象中获取完整产品项的方式不满意,因为我不能只分配一个简单的productid值。

    using (MyContextEntities ctx = new MyContextEntities())
    {
        Orders newOrder = new Orders()
        {
        Name = "Gayle Wynand",
        OrderDate = DateTime.Now,
        IsComplete = true,
        Comments = "test",
        OrderStatusId = 2,
        IsActive = true
        };
        OrderDetails ode = new OrderDetails();
        ode.Products = ctx.Products.First(p => p.Id == 2); // any other way?
        ode.Quantity = 2;
        ode.Rate = 5.2;
        newOrder.OrderDetails.Add(ode);
    
        OrderDetails ode2 = new OrderDetails();
        ode2.Products = ctx.Products.First(p => p.Id == 3); // any other way?
        ode2.Quantity = 3;
        ode2.Rate =6.5;
        newOrder.OrderDetails.Add(ode2);
    
    
        ctx.AddToOrders(newOrder);
        ctx.SaveChanges();
    }
    

    这是插入主细节的正确方法,还是有更好的/另一种方法。

    2 回复  |  直到 13 年前
        1
  •  2
  •   Craig Stuntz    16 年前

    你现在所做的工作会很好。

    如果希望在分配ode.products时避免执行数据库查询,则可以使用以下替代方法:

    // substitute your actual qualified entity set name
    ode.ProductsReference.EntityKey = 
        new EntityKey("MyEntities.ProductsEntitySetName", "Id", 2);
    

    这速度更快,但可读性较差。此外,在加载之前,products属性将为空。但是对于插入,这通常是可以的。

        2
  •  1
  •   Alex James    16 年前

    另一种方法是使用存根对象而不是EntityKeys,即

    var product = new Product {ID = 2};
    ctx.AttachTo("Products", product);
    ode.Product = product;
    

    等等。作为一个额外的奖励,这段代码将来也将与POCO对象一起工作。

    this blog post 有关该技术的更多信息。