locked
Entity Framework and DataGrid - How do I show data form two tables in one DataGrid and maintain the ability to edit the data RRS feed

  • Question

  • Hello everyone,

    I am using WPF and the Entity Framework to work with a SQL Express database. I am new to WPF, LINQ and the Entity Framework so I created a little project to learn with.

    My database has the following tables:

    Items: ID, Name, Description, Cost

    Inventory: ID, Count, ItemID

    where Inventory.ItemID is a foreign key referring to Item.ID

    I created an entity model from the SQL database and i have found using the entity objects to be quick and fun. But, I want to create a Data Grid which shows the all Inventory records and the related Item information:

    Inventory.Count | Items.Name | Items.Cost | Items.Description

    I want only Inventory.Count to be editable. If I was in my home environment of php and webpages I would use the query below to populate the view (hiding the Inventory.ID column) and handle the update post-back myself.

    SELECT Inventory.ID, Inventory.Count, Items.Name, Items.Cost, Items.Description
    FROM Inventory
    LEFT JOIN Items
    ON Inventory.ItemID = Items.ID

    My attempts so far have only created non-editable view sources. I know I could just code the whole user interface myself as I have done with php and mysql but that seems brutish in this environment when such an elegant DataGrid control is available.

    I found another question of a similar nature but it was dated 2009 and only provided general hints:

    Entity Framework, Data Relations, and an Updatable Datagrid

    So, what you probably need to do is write a query that returns the whole entities in an anonymous type or DbDataRecord so that you get back 3 entities rather than 3 properties from each of the underlying tables. Then you can setup your grid to display the props from those entities that you want. You probably will have to do some glue code, though, to get everything to update nicely in the end. This kind of 1-* scenario where you display everything in a single grid just isn't something that the EF can easily do for you out of the box without supplying some custom code to deal with the relationships.

    - Danny

    This helped me understand the underlying concepts but I need code examples to learn from.

    Is there a specific and straightforward way to present an editable Data Grid drawing data from two tables using XAML, WPF, LINQ and the Entity Framework?

    Bonus question: how would I add a column to show a simple computation: Inventory.Count * Item.Cost = InventoryItemTotal ?

    Saturday, June 16, 2012 1:14 PM

Answers

All replies