I have a model with the following structure:
public class ModeloUno
{
public int Id { get; set; }
public string Nombre{ get; set; }
public string Descripcion { get; set; }
public Status Status { get; set; }
}
public class Status
{
public int Id { get; set; }
public string Nombre{ get; set; }
}
With a database query I obtain the fields of ModeloUno plus Status (Id, Name, Description, IdStatus and NameStatus) and set them as follows:
var modelo= rows.Select(r => new ModeloUno
{
Id = r.Field<int>("ID"),
Codigo = r.Field<string>("NAME"),
Descripcion = r.Field<string>("DESCRIPTION"),
Status = r.Field<Status>(???)
});
How do I set Status if it has multiple fields?
Simply do the following:
What is done here is to create a new type variable
Status
using an object initializer , which basically consists of assigning the initial value to each field of the object.In this case, what you want is to assign to
Status.Id
the valueint
that is in the columnIdStatus
, and toStatus.Nombre
the valuestring
that you have in the columnNombreStatus
.PS I strongly recommend that the name of the class and the name of the variable do not match (
Status
), that can lead to a lot of confusion. On the other hand, for the case you expose it would not be necessary to create the classStatus
, you could simply addIdStatus
andNombreStatus
as variables inModeloUno
. Another thing is that the relationship between oneModeloUno
andStatus
outside of one to several. In that case, it would make sense to create the classStatus
and store it insideModeloUno
asList<Status>
.