将相关实体绑定到数据网格

Bind a related entities to a data grid

我正在使用 Entity Framework 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

感谢 Kylo Ren。

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

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