我尝试将数组中的第一封电子邮件显示为DataGrid列中的用户电子邮件。
这就是我获取数据的方式:
IEnumerable<User> dgUsers;
dgUsers = Context.Users.Where(u => u.Location == "UK")
.Include(j => j.Emails).ToList();
这是我的XAML:
<DataGrid x:Name="dataGrid" ItemsSource="{Binding dgUsers}" HorizontalAlignment="Stretch" Margin="10,37,10,10" VerticalAlignment="Stretch"
CanUserAddRows="False" CanUserDeleteRows="False" IsReadOnly="True" AutoGenerateColumns="False">
<DataGrid.Columns >
<DataGridTextColumn Header="Name" Binding="{Binding Name}" />
<DataGridTextColumn Header="Surname" Binding="{Binding Surname}" />
<DataGridTextColumn Header="Location" Binding="{Binding Location}" />
<DataGridTextColumn Header="Email" Binding="{Binding Emails[0].Email}" Width="350" />
<DataGridTextColumn Header="LastLogon" Binding="{Binding LastLogon}" />
</DataGrid.Columns>
</DataGrid>
用户类定义:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Surname { get; set; }
public string Location { get; set; }
public DateTime LastLogon { get; set; }
public virtual ICollection<Mail> Emails { get; set; }
}
public class Mail
{
public int Id { get; set; }
public int UserId { get; set; }
public string Email { get; set; }
}
不确定我做错了什么,网格显示但是电子邮件列是空的?
答案 0 :(得分:1)
常见的方法是创建UserViewModel
,将第一封电子邮件定义为属性。所以你的查询就像是。
IEnumerable<UserViewModel> dgUsers;
dgUsers = Context.Users.Where(u => u.Location == "UK")
.Include(j => j.Emails)
.Select(u => new UserViewModel() { /* some user properties */ Email = u.Emails.FirstOrDefault() }).ToList();
<强>更新强>
ICollection
接口未声明索引器。因此,我建议您使用IList来解决您的问题。