I am having a real issue, and I know that it is because I just don’t know enough. I have searched through about 50 articles and cannot find an answers.
Here are my domain models
Namespace Models
Public Class Article
Public Property ArticleId As Integer
Public Property Author As String
<DisplayFormat(DataFormatString:="{0:D}")>
Public Property CreatedOn As DateTime
<DisplayFormat(DataFormatString:="{0:D}")>
Public Property LastModified As DateTime
<AllowHtml()>
Public Property Content As String
Public Property Title As String
Public Property Excerpt As String
Public Property IsPublic As Boolean
Public Overridable Property Category As ICollection(Of Category)
Public Overridable Property Tags As ICollection(Of Tag)
Public Overridable Property Status As ICollection(Of Status)
Public Overridable Property Comments As ICollection(Of Comment)
End Class
End Namespace
Namespace Models
Public Class Status
Public Property StatusId As Integer
Public Property Name As String
Public Overridable Property Articles As ICollection(Of Article)
End Class
End Namespace
Namespace Models
Public Class Category
Public Property CategoryId As Integer
Public Property Name As String
Public Overridable Property Articles As ICollection(Of Article)
End Class
End Namespace
Namespace Models
Public Class Tag
Public Property TagId As Integer
Public Property Name As String
Public Overridable Property Articles As ICollection(Of Article)
End Class
End Namespace
Here is my ViewModel (based on my domain model)
Namespace ViewModels.Admin
Public Class ArticleViewModel
Public Property Article As Article
Public Property CategoryId As Integer
Public Property StatusId As Integer
Public Property Tags As ICollection(Of Tag)
End Class
End Namespace
I dont know how to save with all of these data crossing patterns. I have tried so many ways now, I do not know where to look. I have tried a few books, but no one really digs into this. I also look at the Contoso University project, but it does not seem like my project. Can anyone help?
If you are using the Entity Framework to do your DAL, you can do this quite easily. Simply build the object from the top down. So in your example, get the article from the ViewModel and populate its navigation properties from the other parts of the View Model.
Don’t worry about wiring up the navigation properties of the sub objects.
You can then add this article to the context using AddObject on the articles collection and all the sub properties should insert and wire up too.
Beware of the sub properties that might already exist in the Db, I have seen EF do inserts on those items even though they have Ids rather than just updating the mapping table etc.