Entity Framework & WPF Datagrid binding

2019-05-24 10:19发布

问题:

I have a pretty simple little app that is using EF and WPF. I'm trying to create a very lightweight 'project tracker' for our small team at work. The classes look like:

class Project
{
    public int ProjectId { get; set; }
    public string Name { get; set; }

    public List<ProjectNote> ProjectNotes { get; set; }

    public string Status { get; set; }
    public string Description { get; set; }

    public string ProjectLead { get; set; }
}

class ProjectNote
{


    public int ProjectNoteId { get; set; }
    public DateTime DateCreated { get; set; }
    public DateTime DateEdited { get; set; }
    public string CreatedBy { get; set; }
    public string LastEditedBy { get; set; }
    public string Detail { get; set; }
    public int ProjectId { get; set; }

}

I want to be able to display the following fields in a datagrid:

  1. Project.Name
  2. Project.Description
  3. (Most Recent)ProjectNote.Detail

Basically, I want to have a Datagrid that allows my user to see the most recent notes for a Project and edit them if need be.

I'm having trouble figuring out how to structure my code (I'm using Code First/POCO) to allow the user to create a new ProjectNote from the Datagrid view. I don't know if I need another property of my Project class to allow for a single ProjectNote, or if I can code this (through a ViewModel) to properly instantiate a new ProjectNote when the user is editing a Datagrid that contains the Project data.

How can I create a datagrid that allows editing/creation across multiple entities?

回答1:

I would suggest creating a ViewModel, perhaps ProjectNoteViewModel, which contains the Note as well as the Project. Then, you bind your collection/list of ProjectNoteViewModels to the DataGrid.

Alternatively, you could add a Project navigation property to the ProjectNote class, which would allow you to include the Project.Name and Project.Description in the DataGridRow for the ProjectNote. If there is little or no business logic/complexity to this relationship, then this approach will work, but if there is any complexity or business rules you need to enforce, I'd recommend using a ViewModel.

This article provides a good walk through of using the DataGrid and MVVM together. Basically, if you have DataBound the DataGrid to a list of some sort, the DataGrid will automatically create a new instance of your object for you and insert it into the collection when the user clicks the empty row at the bottom of the grid.