如何在 C# 中将两个数据源绑定到数据网格中

我的问题如下:我有一个使用实体框架的“salesTable”数据网格,我用这段代码加载数据网格:


salesDataGrid.ItemsSource = _db.salesTables.ToList();

salesTable 的列之一是 customerId,它是 customerTable 的外键,现在我想在数据网格中显示 customerName 而不是 customerId,但我不知道如何。


销售表如下:


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

请帮忙!


子衿沉夜
浏览 50回答 1
1回答

慕勒3428872

创建这个视图模型:&nbsp; public class GridViewModel&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; public int SaleId { get; set; }&nbsp; &nbsp; &nbsp; &nbsp; public string CustomerName { get; set; }&nbsp; &nbsp; &nbsp; &nbsp; //other properties you want&nbsp; &nbsp; }然后在查询中使用 GridViewModel:var result = _db.salesTables.Include(x => x.customerTable)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; .Select(x => new GridViewModel()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;SaleId = x.saleId,&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;CustomerName = x.customerTable.CustomerName&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;}).ToList();最后:salesDataGrid.ItemsSource = result;
打开App,查看更多内容
随时随地看视频慕课网APP