2016-07-23 32 views
0

我有3个表格:库存,库存地点,库存量。库存包含项目描述。 InventoryLocations包含位置描述。 InventoryCounts是一个包含InventoryID,LocationID和该位置项目数的桥表。我可以使用实体框架相互引用多个新项目而不必先保存上下文吗?

当我导入一个文件时,所有3个都可以是新的。因此,在上下文中,我想添加库存项目并让DB/EF生成InventoryID。然后,我想添加一个位置描述让数据库生成ID。然后,使用为“库存”项目生成的ID以及为该位置生成的ID向InventoryCounts表添加新记录。我还想使用一个上下文并只有一个SaveChanges来做到这一点。

从我读过的内容来看,这看起来完全可行,但我对导航属性或Fluent API不够了解。使用下面的代码,不起作用。

我知道我大概可以解析数据并拉入所有位置,然后保存。然后拉入所有库存,然后保存。然后添加计数。这只是低效率。

的示例代码如下:

Imports System 
Imports System.Collections.Generic 
Imports System.ComponentModel.DataAnnotations 
Imports System.ComponentModel.DataAnnotations.Schema 
Imports System.Data.Entity.Spatial 

Public Class Test 
'' Test Class 
Public Sub test() 

    Using ctx As New PIOCContext 
     Dim Inv = ctx.App_Inventory 
     Dim Loc = ctx.App_InventoryLocations 
     Dim InvCounts = ctx.App_InventoryCounts 

     Dim i As New App_Inventory() With {.ItemName = "Widget"} 
     Inv.add(i) 

     Dim l As New App_InventoryLocation() With {.Location = "Foo"} 
     Loc.Add(l) 

     Dim cnt As New App_InventoryCount() With {.InventoryID = i.InventoryID, .Qty = 1, .QtyUOM = "Each", .LocationID = l.LocationID} 
     InvCounts.Add(cnt) 

     ctx.SaveChanges() 
    End Using 

End Sub 

End Class 


'' Models 
<Table("dev.App_InventorySubLocations")> 
Partial Public Class App_InventoryLocation 
<Key> 
<Column(TypeName:="uint"), DatabaseGenerated(DatabaseGeneratedOption.Identity)> 
Public Property LocationID As Long 

<Required> 
<StringLength(45)> 
Public Property Location As String 

End Class 


<Table("dev.App_InventoryCounts")> 
Partial Public Class App_InventoryCount 


<Key> 
<Column(Order:=0, TypeName:="uint")> 
<DatabaseGenerated(DatabaseGeneratedOption.None)> 
Public Property InventoryID As Long 

<Key> 
<Column(Order:=1, TypeName:="uint")> 
<DatabaseGenerated(DatabaseGeneratedOption.None)> 
Public Property LocationID As Long 

<Column(TypeName:="uint")> 
Public Property Qty As Long 

<Required> 
<StringLength(45)> 
Public Property QtyUOM As String 

Public Overridable Property Inventory As App_Inventory 
Public Overridable Property Location As App_InventoryLocation 

End Class 

Partial Public Class MyContext 
    Inherits DbContext 
Public Sub New() 
    MyBase.New("name=MyContext") 
End Sub 

Public Overridable Property App_Inventory As DbSet(Of App_Inventory) 
Public Overridable Property App_InventoryCounts As DbSet(Of App_InventoryCount) 
Public Overridable Property App_InventoryLocations As DbSet(Of App_InventoryLocation) 

End Class 
+1

只要给'InventoryCount'导航属性'Inventory'和'Location'并分配'Inventory = i'和'Location = l'。 –

+0

谢谢格特!我想我只是在想它。我非正式地将你的评论标记为答案(因为我不能正式这样做)。 –

回答

0

随着格特上述建议,得到的答复是改变代码添加到阅读:

Dim cnt As New App_InventoryCount() With {.InventoryID = i.InventoryID, .Qty = 1, .QtyUOM = "Each", .Location = l} 

作为一个方面说明,我也需要改变我所有的无符号整数都是整数。显然实体框架不喜欢UInt或大UInt的。 See post here

相关问题