开发者

How to Implement Entity Framework on this example?

I have been working thru this WPF example and am trying to hook it up to my database using Entity Framework but am confused on how to do this. Can someone please offer some guidance on how this would be done?

The code has the following in 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();
    }

which is where I assume the hook to the database would happen but not sure how. I can create the Model.edmx file to connect to the database but not sure how to physically get the list of customers from the database.

Also, this example uses a List of开发者_StackOverflow社区 Customers but most examples I have gone through use ObservableCollection for this type of data. Is one preferable over the other and why?

TIA,

Brian Enderle


My MVVM/EF projects typically load entities directly into the ViewModels or Into light collections in the view models. I don't create any kind of custom repository to sit between them.

Generally my ViewModels do one of two things,

  1. Retrieves data on instancing
  2. Takes an entity as a constructor argument.

When I retrieve data on instance, I generally use a background worker class, which queries the context, puts the results in a list, and passes the list out. The Work Completed method then puts the entities into viewmodels and puts the ViewModels in a ObservableCollection.

Similar to this:

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

In ViewModels that take an entity as an argument, they often take a context as argument, especially if something is a short time-span operation. Otherwise I detach entities from the context in the even something goes hay-wire with the database or the connection is lost or something.

To answer your second question, ObservableCollections are Enumerable collections that have collection change notification implemented. The collection will notify the UI when a new item is added/removed/moved. Typically any time I have entities that are going to be viewed or displayed in the UI, I host them in an Observable Collection. Otherwise I use something simpler, a List normally.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜