barsan barsan - 1 month ago 12
C# Question

How to return multiple rows using LINQ lambda expression from SQL server 2014?

I'm trying to fetch data from SQL Server 2014 using LINQ Lambda expression which the requirement of my project. But as I'm new to LINQ so, I think I'm doing something wrong with the code here and I'm getting error. I can fetch only one row without any error but if I put condition to fetch multiple row then I get error.

Here is my code:

This is the repository class:

public DettagliModel GetByIdDoc(int id)
{
using (var dbCtx = new USDevEntities())
{
var dettagli = dbCtx.Dettaglis.Where(x => x.IDDoc == id);
if (dettagli != null)
{
return ConvertTo(dettagli); // Getting error here
}
else
{
return null;
}
}

}


public DettagliModel ConvertTo(Dettagli entity)
{
var model = Mapper.Map<DettagliModel>(entity);
return model;
}


I'm Getting this error:


Argument 1: cannot convert from 'System.Linq.IQueryable' to 'DAL.Service.Entity.Dettagli' Core.Service


This error is hitting while writing the code but if I put after

.Where(x => x.IDDoc == id).FirstOrDefault();


Then the error goes off.
Please suggest me what can I do to solve this as I need to fetch multiple rows so I cannot use FirstOrDefault() method. Thanks.

Answer

Where extension method returns an IQueryable<T>, which means it is more than one element. If you want to map multiples entities to a different model using Automapper, then I suggest you use ProjectTo<T> extension method:

public IEnumerable<DettagliModel> ConvertTo(IQueryable<Dettagli> entities)
{

    return entities.ProjectTo<DettagliModel>().ToList();
}

public IEnumerable<DettagliModel> GetByIdDocs(int id)
{
    using (var dbCtx = new USDevEntities())
    {
        return ConvertTo(dbCtx.Dettaglis.Where(x => x.IDDoc == id));

    }

}