my problem is the following : I have a datagrid of "salesTable" using entity framework, I load the datagrid with this code :
salesDataGrid.ItemsSource = _db.salesTables.ToList();
one of the columns of salesTable is customerId which is a foreign key of customerTable, now I want to show the customerName instead of the customerId in the datagrid but I don't know how.
salesTable is as the following :
public int saleId { get; set; }
public Nullable<int> customerId { get; set; }
public Nullable<System.DateTime> saleDate { get; set; }
public Nullable<int> invoiceId { get; set; }
public Nullable<decimal> total{ get; set; }
public virtual customerTable customerTable { get; set; }
public virtual fac fac { get; set; }
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
public virtual ICollection<Sale_Detail> Sale_Detail { get; set; }
Please help!
Create this ViewModel:
public class GridViewModel
{
public int SaleId { get; set; }
public string CustomerName { get; set; }
//other properties you want
}
Then use GridViewModel in query:
var result = _db.salesTables.Include(x => x.customerTable)
.Select(x => new GridViewModel()
{
SaleId = x.saleId,
CustomerName = x.customerTable.CustomerName
}).ToList();
and finally:
salesDataGrid.ItemsSource = result;