我正在使用LINQ从数据库中提取数据,并且有一个关于从子查询中提取对象的问题。这是我要拉的课程:
public class Users
{
public Users()
{
SerialNumbers = new HashSet<SerialNumbers>();
}
/// <summary>
/// The User's Unique Id
/// </summary>
public Guid Id { get; set; }
/// <summary>
/// The Users name
/// </summary>
public string Name { get; set; }
/// <summary>
/// The Users email. This can be null/empty string
/// </summary>
public string Email { get; set; }
public virtual ICollection<SerialNumbers> SerialNumbers { get; set; }
}
如何从序列号集合中选择第一个元素而不是整个集合本身?
由于
答案 0 :(得分:0)
var serial = context.Users.FirstOrDefault().SerialNumbers.FirstOrDefault();
答案 1 :(得分:0)
您应该创建一个DataTransferObject并映射到它:
context.Users.Select(x => new UserDto
{
Id = x.Id,
Name = x.Name,
Email = x.Email,
SerialNumber = x.SerialNumbers.FirstOrDefault()
});