我有一个真正的问题,我知道这是因为我不够了解。我搜索了大约50篇文章,但找不到答案。
以下是我的域名模型
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
这是我的ViewModel(基于我的域模型)
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
我不知道如何使用所有这些数据交叉模式进行保存。我现在尝试了很多方法,我不知道在哪里看。我试过几本书,但没有人真正深入研究这本书。我也看看Contoso大学项目,但它似乎不是我的项目。有人可以帮忙吗?
答案 0 :(得分:1)
如果您使用实体框架来执行DAL,则可以非常轻松地执行此操作。只需从上到下构建对象即可。因此,在您的示例中,从ViewModel获取文章,并从View模型的其他部分填充其导航属性。
不要担心连接子对象的导航属性。
然后,您可以使用文章集合上的AddObject将此文章添加到上下文中,并且所有子属性也应插入并连接。
请注意Db中可能已经存在的子属性,我已经看到EF会对这些项进行插入,即使它们有ID但不只是更新映射表等。