【问题标题】:Bind a related entities to a data grid将相关实体绑定到数据网格
【发布时间】:2016-05-31 11:30:58
【问题描述】:

我正在使用实体框架 6.1。在我的模型中,有两个实体 CountryDistricts。如:

public class Country
{
    public Country()
    {
        Districts = new HashSet<District>();
    }

    public int CountryId { get; set; }
    public string CountryArabicName { get; set; }
    public string CountryEnglishName { get; set; }
    public string NationalityArabicName { get; set; }
    public string NationalityEnglishName { get; set; }

    public virtual ICollection<District> Districts { get; private set; }
}

public class District
{
    public int DistrictId { get; set; }
    public int CountryId { get; set; }
    public string DistrictArabicName { get; set; }
    public string DistrictEnglishName { get; set; }
    public Country Country { get; set; }
}

所以,国家有很多省。

在我的 ViewModel 中:

private IEnumerable<District> _districts;
public IEnumerable<District> Districts
{
    get { return _districts; }
    set { SetProperty(ref _districts, value); }
}

然后,填写:

Districts =  (from district in cmsDbContext.Districts
                orderby district.DistrictId
                select district).ToList();

在视图中:

<UserControl.DataContext>
    <vm:DistrictVm/>
</UserControl.DataContext>

<DataGrid Height="308" AutoGenerateColumns="False" ItemsSource="{Binding Districts}">
        <DataGrid.Columns>
            <DataGridTextColumn Binding="{Binding Path=DistrictArabicName}" Header="District" IsReadOnly="True"/>
            <DataGridTextColumn Binding="{Binding Path=Country.CountryArabicName}" Header="Country" IsReadOnly="True" />
        </DataGrid.Columns>
 </DataGrid>

现在,DistrictArabicName 已正确显示。但是 Country.CountryArabicName

没有

我该怎么做才能解决这个问题?我想检索 Country.CountryArabicName

【问题讨论】:

  • CountryArabicName 是 Country 类的属性,您的视图模型中是否有 country 对象(即在 DistrictVm 中)?还是您有其他国家对象的视图模型?
  • @Kylo Ren。我在 DistrictVm 中没有 Country 对象。但是,我确实有 CountryVm。它们之间是什么关系,我没弄明白!起初,我以为我可以从 District 获得 Country
  • 您的绑定是正确的,但正如您所说,它不起作用意味着 District 类的 Country 属性为 null 或 CountryArabicName 属性为 null/未设置。确保这些属性具有值。我建议国家对象,希望在 ViewModel 中你可能有一个国家集合,它可以使用相对源绑定绑定到你的列绑定。您需要对此进行调试以找出问题所在。
  • @Kylo Ren。正确的!。它们是空的。我改变了 public Country Country { get;放; }public virtual Country Country { get;放; },刚刚添加了virtual,现在不为null,但我得到的是“erw”而不是真实数据。
  • 可能在地区集合中填充国家值是一种简单的方法,然后访问整个其他视图模型。无论您在哪里填充此区域集合,都使用它们填充国家/地区值,UI 逻辑在此基础上是正确的

标签: c# wpf xaml datagrid viewmodel


【解决方案1】:

感谢 Kylo Ren。

我为解决问题所做的工作: - 删除虚拟以禁用延迟加载。数据太小了。少于 20 条记录。 - 删除所有迁移和数据库。 - 重新启用迁移,并更新数据库。

现在,我的示例正在运行。

【讨论】:

    猜你喜欢
    • 2011-12-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多