【问题标题】:How to bind two source of data into a datagrid in c#如何在c#中将两个数据源绑定到数据网格中
【发布时间】:2019-04-21 18:21:00
【问题描述】:

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

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

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

salesTable如下:

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

请帮忙!

【问题讨论】:

  • 我们可以看看salesTables 是如何定义和填充的吗?
  • 请再看一遍帖子,谢谢!

标签: c# wpf entity-framework data-binding datagrid


【解决方案1】:

创建这个 ViewModel:

  public class GridViewModel
    {
        public int SaleId { get; set; }
        public string CustomerName { get; set; }
        //other properties you want
    }

然后在查询中使用 GridViewModel:

var result = _db.salesTables.Include(x => x.customerTable)
                            .Select(x => new GridViewModel()
                          {
                               SaleId = x.saleId,
                               CustomerName = x.customerTable.CustomerName
                           }).ToList();

最后:

salesDataGrid.ItemsSource = result;

【讨论】:

    猜你喜欢
    • 2011-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-23
    • 2013-03-28
    • 2011-05-28
    相关资源
    最近更新 更多