best practise/way for master detail / multi table Insert in Entity Framework

前端 未结 2 718
被撕碎了的回忆
被撕碎了的回忆 2020-12-16 23:49

My table structure is this

Orders
------ 
Id int identity
OrderDate smalldatetime
OrderStatusid tinyint

Products
--------
Id int identity
Name varchar(50)

         


        
相关标签:
2条回答
  • 2020-12-17 00:22

    What you are doing now will work just fine.

    If you would like to avoid doing a database query when assigning ode.Products, then you could use the following alternative:

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

    This is faster, but less readable. Also, the Products property will be null until you Load it. But for an insert, this is often OK.

    0 讨论(0)
  • 2020-12-17 00:25

    Another approach would be to use Stub Objects rather than EntityKeys i.e.

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

    etc. As an added bonus this code will work with POCO objects too in the future.

    See this blog post for more information on that technique.

    0 讨论(0)
提交回复
热议问题