You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#搭配EF Core时如何在DataGrid中绑定关联实体的子字段

步骤1:修正EF Core查询,确保导航属性预加载

你当前的查询没有加载关联的Product导航属性,直接绑定会因为Product为null拿不到对应值,需要用Include方法预加载关联数据:

// 需先引入命名空间 using Microsoft.EntityFrameworkCore;
ObservableCollection<ProductInventory> Products = 
   new ObservableCollection<ProductInventory>(context.ProductInventories.Include(p => p.Product).ToList());

步骤2:DataGrid列绑定嵌套属性

直接在绑定路径中填写多级属性路径即可,两种常用实现方式:

方式1:手动定义DataGrid列(推荐,可控性更高)

在XAML代码中直接指定绑定路径为Product.Name:

<DataGrid ItemsSource="{Binding Products}" AutoGenerateColumns="False">
    <DataGrid.Columns>
        <!-- 其他业务列示例,比如库存ID -->
        <DataGridTextColumn Header="库存ID" Binding="{Binding ProductInventoryId}"/>
        <!-- 绑定产品名称列 -->
        <DataGridTextColumn Header="产品名称" Binding="{Binding Product.Name, TargetNullValue='无关联产品信息'}"/>
    </DataGrid.Columns>
</DataGrid>

这里额外添加的TargetNullValue配置用于处理个别Product为空的场景,避免列显示空白。

方式2:简化绑定(适配自动生成列场景)

可以直接在ProductInventory实体类中新增只读的ProductName属性,不需要修改原有逻辑,绑定更简单:

public class ProductInventory 
{ 
    public long ProductInventoryId { get; set ;}
    public long ProductId { get; set; }
    public virtual Product Product { get; set; }
    // 新增只读属性,直接返回关联产品名称
    public string ProductName => Product?.Name;
}

之后直接绑定该属性即可:

<DataGridTextColumn Header="产品名称" Binding="{Binding ProductName}"/>

额外注意事项

你提到存在同名的视图模型类ProductInventory,如果你的DataGrid实际绑定的是视图模型集合而非EF实体集合,记得在视图模型层维护Product引用,或者直接把ProductName映射为视图模型的独立属性,绑定更稳妥。

内容的提问来源于stack exchange,提问作者Hossein

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 10:27:03