I'm working with Entity Framework code first, I'm putting together a query but from my entity I only need the first two attributes for which I had to create another class with the attributes I need to not bring me the whole entity.
public class Proveedor
{
public int ProveedorId { get; set; }
public string RazonSocial { get; set; }
public string DocumentoIdentidad { get; set; }
public string Direccion { get; set; }
public string Fijo { get; set; }
public string Celular { get; set; }
public string Representante { get; set; }
public string Email { get; set; }
public virtual ICollection<Producto> Productos { get; set; }
public virtual ICollection<Marca> Marcas { get; set; }
}
Extended class
public class ProveedorExtend
{
public int Id { get; set; }
public string Descripcion { get; set; }
}
I need to match the properties
public IEnumerable<ProveedorExtend> SelectList(int? codigo, string nombre)
{
var result = (from p in Context.Proveedores
select new ProveedorExtend()
{
Id = p.ProveedorId,
Descripcion = p.RazonSocial
})
So that you can apply a Where
where ((!codigo.HasValue) || (p.Codigo.Contains(codigo.Value)))
&& ((nombre == null) || (p.Nombre.Contains(nombre)))
select p).ToList();
How can I do this query?
public List<ProveedorExtend> SelectList(int? codigo, string nombre)
{
using(DbContext context = new DbContext())
{
var result = (from p in context.Proveedores
where ((!Id.HasValue) || (p.Id.Contains(Id.Value)))
&& ((Descripcion == null) || (p.Descripcion.Contains(nombre)))
select p).ToList();;
return result;
}
}
But I need to match the entities before making that query. I hope to have explained. The description would be: I try to make a query that serves me for two conditions through that query I can ask for the id, how can I ask for the description, like for example if I have a table that has, 1- Juan 2-Miguel 3-Marcos 4 José What I want is to do a like, researching constains is the one that makes a like, but the problem is that I can not apply to the whole entity, if it were SQL I would do a query SELECT Id, description FROM Suppliers, .... but in EF I can not do that would bring me the whole entity that is why I have to separate it in my SupplierExtend class where I put the attributes I need but for it to work I have to match it to the Suppliers, in my Context I do not see VendorExtends I can not apply directly.
I am left with the query thanks to Leandro and Carlos Muñoz.
public IEnumerable<ProveedorExtend> SelectList(int? codigo, string nombre)
{
var result = (from p in Context.Proveedores
where ((!codigo.HasValue) || (p.ProveedorId == codigo.Value)) &&
((nombre == null) || (p.RazonSocial.Contains(nombre)))
select new ProveedorExtend()
{
Id = p.ProveedorId,
Descripcion = p.RazonSocial
}).ToList();
return result;
}