从两个表中检索数据并填充 DataGrid 实体框架

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

http://img1.mukewang.com/61ac760c0001bead04430342.jpg

我正在使用DataGrid具有以下列的一个,如图所示。

http://img1.mukewang.com/61ac76190001ed5707070198.jpg

这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; }

}


九州编程
浏览 175回答 1
1回答

回首忆惘然

如果Customer是 的导航属性Invoice,您可以使用预先加载来加载它,例如: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" />
打开App,查看更多内容
随时随地看视频慕课网APP