Search code examples
c#wpfwpfdatagrid

Inserting item into DataGrid


I have the following tables:

enter image description here

I'm using Entity Framework Database First, therefore the following entity class is generated:

public partial class Sal1 {
    public string SaleID { get; set; }
    public string ItemID { get; set; }
    public int Quantity { get; set; }
    public decimal Total { get; set; }

    public virtual Item Item { get; set; }
    public virtual Sale Sale { get; set; }
}

Then put the Sal1 rows into a datagrid like this:

private List<Sal1> saleItems = new List<Sal1>();
...
var query = from sa in db.Sal1
            where sa.SaleID.Equals(tempSale)
            select sa;
foreach(Sal1 si in query) {
    saleItems.Add(si);                    
}
...
dgDetails.ItemsSource = saleItems;

But it turns out like this: enter image description here

My question is, how should I tweak the query above so that I get the equivalent of the following SQL:

select T0.SaleID, T0.ItemID, T1.Name, T0.Quantity, T0.Total 
from Sal1 T0 inner join Item T1 on T0.ItemID = T1.ItemID;

Thanks in advance.


EDIT: I seem to have found a solution, but I had to do this:

var query = from sa in db.Sal1
        where sa.SaleID.Equals(tempSale)
        select new  { sa.SaleID, sa.ItemID, sa.Item.Name, 
            sa.Item.Manufacturer, sa.Quantity, sa.Total };

And I had to change the type of saleItems to object.

private List<object> saleItems = new List<object>();

Is this the best way to do it?


Solution

  • Just like SQL, LINQ also supports JOINs. You can read more about their syntax here. You should change your query accordingly to get your results. Instead of spoonfeeding the exact answer, I'm guiding you to a more detailed explanation, as it contains valuable information that will help you in the future too.