使用WPF

时间:2018-04-14 17:38:58

标签: c# wpf entity-framework datagrid

我在实体框架中有两个相关实体,Stock然后是Suppliers,其中一个股票实体可以有一个供应商,供应商可以有多个股票项目。

我有一个数据网格,我想在其中显示有关股票的所有数据,例如Id,Name,Price等,并为其包含SuppliersId

在下面的屏幕截图中,我希望它显示SuppliersId所在的供应商,但我无法获取它,因此它不包含整个对象的字符串。

Screenshot of program

股票类

class Stock
{
    public Stock()
    {
        this.SalesInvolvedIn = new HashSet<Sales>();
    }

    public int StockId { get; set; }
    public string StockName { get; set; }
    public int StockPrice { get; set; }
    public string StockType { get; set; }
    public ICollection<Sales> SalesInvolvedIn { get; set; }

    public Suppliers Suppliers { get; set; }
}

获取数据

public List<Stock> GetStock()
{                        
    return StockManagementDatabaseContext.Stocks.Include("Suppliers").ToList();
}

更新数据网格

private void UpdateStockList()
{
    List<Stock> stocklist = repository.GetStock();

    this.StockDataGrid.ItemsSource = stocklist;
}

我将如何做到这一点?

编辑:显示供应商类

class Suppliers
{
    public int SuppliersId { get; set; }
    public string SupplierName { get; set; }
    public string ContactPerson { get; set; }
    public int PhoneNumber { get; set; }

    public ICollection<Stock> StockSold { get; set; }
}

1 个答案:

答案 0 :(得分:0)

如果我理解正确您只想显示供应商ID?我想到了两种方法:ViewModel或不使用XAML中数据网格中的自动生成列。

您可以像这样创建ViewModel

public class StockViewModel
{
    public int StockId { get; set; }
    public string StockName { get; set; }
    public int StockPrice { get; set; }
    //etc....
    public int SupplierId { get; set; }
}

获取数据:

public List<StockViewModel> GetStock()
{                        
    return StockManagementDatabaseContext.Stocks.Include("Suppliers")
    .Select(a => new StockViewModel
    {
         StockId = a.StockId,
         StockName = a.StockName,
         StockPrice = a.StockPrice,
         //and any other you may wish to include
         SupplierId = a.Suppliers.SuppliersId
    }).ToList();
}

加载到您的网格

private void UpdateStockList()
{
   this.StockDataGrid.ItemsSource = repository.GetStock();
}

或者,您可以通过将AutoGenerateColumns设置为错误

来选择希望网格在XAML中绑定的内容
    <DataGrid Name="StockDataGrid"
              ItemsSource="{Binding}"             
              AutoGenerateColumns="False">
        <DataGrid.Columns>
            <DataGridTextColumn Header="ID" Binding="{Binding StockId }"></DataGridTextColumn>
            <DataGridTextColumn Header="Name" Binding="{Binding StockName }"></DataGridTextColumn>
            <DataGridTextColumn Header="Price" Binding="{Binding StockPrice}"></DataGridTextColumn>
            <DataGridTextColumn Header="Supplier ID" Binding="{Binding Suppliers.SupplierId}"></DataGridTextColumn>
        </DataGrid.Columns>
    </DataGrid>