'Fetch the Properties from Nullable Child Collection using Entity Framework IQueryable
I have 2 models
Contact
public int Id{ get; set; }
public string FirstName{ get; set; }
public string LastName{ get; set; }
public string Email{ get; set; }
public virtual ICollection<Address> Addresses { get; set; }
Address
public int ContactId { get; set; }
public bool IsPrimary { get; set; }
public string Line1 { get; set; }
public string Line2 { get; set; }
public string Line3 { get; set; }
...... and some more props
While making a database call using Entity Framework i have to convert the Entity to a custom View Model and i am using the following code now
var dataset = await query.Select(c => new ContactListModel
{
Id = c.Id,
FirstName = c.FirstName,
LastName = c.LastName,
Email = c.Email,
Line1 = (c.Addresses.FirstOrDefault(a => a.IsPrimary) != null) ? c.Addresses.FirstOrDefault(a => a.IsPrimary).Line1 : "",
Line2 = (c.Addresses.FirstOrDefault(a => a.IsPrimary) != null) ? c.Addresses.FirstOrDefault(a => a.IsPrimary).Line2 : "",
Line3 = (c.Addresses.FirstOrDefault(a => a.IsPrimary) != null) ? c.Addresses.FirstOrDefault(a => a.IsPrimary).Line3 : "",
Line4 = (c.Addresses.FirstOrDefault(a => a.IsPrimary) != null) ? c.Addresses.FirstOrDefault(a => a.IsPrimary).Line4 : "",
Address = c.Addresses.FirstOrDefault(a => a.IsPrimary),
}).OrderByDynamic(sortBy, sortDirection).Paginate((tableState.Page * tableState.PageSize), tableState.PageSize).ToListAsync();
OrderByDynamic and Paginate are extension methods used to handle pagination and sorting
Can we assign the values of Line1,Line2,Line3 etc in any other ways. At present every line or for every properties i am checking the Primary Address from the list and checking for null and then assign the properties I have to assign couple more properties like Country Town Postcode etc as well from the address collection
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
