从两个表中检索数据并填充DataGrid Entity Framework

时间:2018-08-20 12:23:07

标签: c# sql-server database wpf entity-framework

我正在使用实体框架。我的数据库“客户和发票”中有2个表。发票表中有一列CustomerID作为外键,以引用该客户。
Tables in database

我正在使用DataGrid,它具有以下各列,如图所示。

Data Grid

DataGrid应显示发票表中的数据和客户表中的客户名称。请帮我如何查询?
DataGrid

<DataGrid IsReadOnly="False" Margin="0 10 0 0" Background="white" Name="InvoiceGrid" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <DataGridTextColumn Header="Invoice ID" IsReadOnly="True" MinWidth="100"/>
        <DataGridTextColumn Header="Date" IsReadOnly="True" MinWidth="100" />
        <DataGridTextColumn Header="Customer" IsReadOnly="True" MinWidth="250" />
        <DataGridTextColumn Header="Quantity" IsReadOnly="True" MinWidth="80" />
        <materialDesign:MaterialDataGridTextColumn IsReadOnly="True" Header="Total" MinWidth="150" />  

上下文类

public partial class Intelliventory_DBEntities : DbContext
{
    public Intelliventory_DBEntities()
        : base("name=Intelliventory_DBEntities")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        throw new UnintentionalCodeFirstException();
    }

    public virtual DbSet<Category> Categories { get; set; }
    public virtual DbSet<Customer> Customers { get; set; }
    public virtual DbSet<Employee> Employees { get; set; }
    public virtual DbSet<Invoice> Invoices { get; set; }
    public virtual DbSet<InvoiceItem> InvoiceItems { get; set; }
    public virtual DbSet<Product> Products { get; set; }
    public virtual DbSet<Purchase> Purchases { get; set; }
    public virtual DbSet<Supplier> Suppliers { get; set; }
    public virtual DbSet<sysdiagram> sysdiagrams { get; set; }
}

1 个答案:

答案 0 :(得分:0)

如果CustomerInvoice的导航属性,则可以使用紧急加载方式加载它,例如:

var context = new Intelliventory_DBEntities();
InvoiceGrid.ItemsSource = context.Invoices.Include(x => x.Customer).ToList();
//...
context.Dispose();

然后您可以将列绑定到导航属性:

<DataGridTextColumn Header="Invoice ID" Binding="{Binding InvoiceID}" IsReadOnly="True" MinWidth="100"/>
<DataGridTextColumn Header="Date" Binding="{Binding Date}" IsReadOnly="True" MinWidth="100" />
<DataGridTextColumn Header="Customer" Binding="{Binding Customer.CustomerName}" IsReadOnly="True" MinWidth="250" />