我一直在通过this WPF示例工作,并尝试使用Entity Framework将其连接到我的数据库,但我对如何执行此操作感到困惑。有人可以就如何做到这一点提供一些指导吗?
代码在CustomerRepository.cs中有以下内容
static List<Customer> LoadCustomers(string customerDataFile)
{
// In a real application, the data would come from an external source,
// but for this demo let's keep things simple and use a resource file.
using (Stream stream = GetResourceStream(customerDataFile))
using (XmlReader xmlRdr = new XmlTextReader(stream))
return
(from customerElem in XDocument.Load(xmlRdr).Element("customers").Elements("customer")
select Customer.CreateCustomer(
(double)customerElem.Attribute("totalSales"),
(string)customerElem.Attribute("firstName"),
(string)customerElem.Attribute("lastName"),
(bool)customerElem.Attribute("isCompany"),
(string)customerElem.Attribute("email")
)).ToList();
}
这是我假设数据库的钩子会发生但不确定如何。我可以创建Model.edmx文件以连接到数据库,但不确定如何从数据库中物理获取客户列表。
此外,此示例使用客户列表,但我已经使用的大多数示例都使用ObservableCollection来处理此类数据。一个优于另一个,为什么?
TIA,
Brian Enderle
答案 0 :(得分:0)
我的MVVM / EF项目通常将实体直接加载到视图模型中的ViewModel或Into集合中。我不会在它们之间创建任何类型的自定义存储库。
通常我的ViewModel会做两件事之一,
当我在实例上检索数据时,我通常使用后台工作者类,它查询上下文,将结果放入列表中,并将列表传递出去。 Work Completed方法然后将实体放入viewmodel并将ViewModel放入ObservableCollection中。
与此类似:
Private WithEvents GetProjectsBackgroundWorker As BackgroundWorker
Private _Projects As New ObservableCollection(Of ProjectViewModel)
Public Sub New()
GetProjectsBackgroundWorker = New BackgroundWorker
GetProjectsBackgroundWorker.RunWorkerAsync()
End Sub
Public Property Projects() As ObservableCollection(Of ProjectViewModel)
Get
Return _Projects
End Get
Set(ByVal value As ObservableCollection(Of ProjectViewModel))
_Projects = value
End Set
End Property
#Region " GetProjects"
Private Sub GetProjectsBackgroundWorker_DoWork(ByVal sender As Object, ByVal e As System.ComponentModel.DoWorkEventArgs) Handles GetProjectsBackgroundWorker.DoWork
Dim results = From proj As Project In Context.Projects Where proj.flgActive = True And proj.flgReview = True Select proj
Dim ProjList As New List(Of Project)(results)
e.Result = ProjList
End Sub
Private Sub GetProjectsBackgroundWorker_RunWorkerCompleted(ByVal sender As Object, ByVal e As System.ComponentModel.RunWorkerCompletedEventArgs) Handles GetProjectsBackgroundWorker.RunWorkerCompleted
If e.Error Is Nothing Then
For Each p As Project In e.Result
Projects.Add(New ProjectViewModel(p, Context))
Next
Else
End If
End Sub
#End Region
在将实体作为参数的ViewModel中,它们通常将上下文作为参数,特别是如果某些内容是短时间跨度操作。否则,我将实体从上下文中分离出去甚至与数据库发生干扰,或者连接丢失或其他什么。
要回答第二个问题,ObservableCollections是可实现集合更改通知的可枚举集合。当添加/删除/移动新项目时,该集合将通知UI。通常,只要我在UI中查看或显示实体,我就会将它们托管在Observable Collection中。否则我会使用更简单的东西,通常是List。