简体   繁体   中英

Bind a related entities to a data grid

I am using Entity Framework 6.1. In my model, two entities Country and Districts . as:

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

So, Country has many Provinces.

In my ViewModel:

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

Then, fill it:

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

In the View:

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

Now, DistrictArabicName is shown correctly. But nothing for Country.CountryArabicName

What shall I do to solve this?. I want to retrieve Country.CountryArabicName

Thanks to Kylo Ren.

What I did to solve the problem: - Remove virtual to disable lazy loading. The data is too small. less than 20 records. - Delete all migrations and the database. - Re-enable migration again, and update the database.

Now, my example is working.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM