views:

51

answers:

2

I am using Linq-to-sql as an ORM. I wrote this innerjoin

public IQueryable<Material> FindAllMaterials()
 {
   var materials=from m in db.Materials
               join Mt in db.MeasurementTypes on m.MeasurementTypeId equals Mt.Id
               select new { m.Mat_id, 
               m.Mat_Name, 
               Mt.Name, 
                m.Mat_Type };

  return materials;
 }

But when i compile this i got an error

Cannot implicitly convert type 'System.Linq.IQueryable<AnonymousType#1>' 
to 'System.Linq.IQueryable<CrMVC.Models.Material>'. 
An explicit conversion exists (are you missing a cast?)

Am i missing some thing... Any suggestion....

EDIT:

My sql query

select M.Mat_id,M.Mat_Name,T.Name as Measurement,M.Mat_Type as Description
from Material as M inner join 
    MeasurementTypes as T on M.MeasurementTypeId = T.Id where M.Is_Deleted=0
+1  A: 

try this one

just added the "new Material()"....

public IQueryable<Material> FindAllMaterials()
 {
   var materials=from m in db.Materials
               join Mt in db.MeasurementTypes on m.MeasurementTypeId equals Mt.Id
               select new Material(){ Mat_id = m.Mat_id, 
                Mat_Name = m.Mat_Name, 
                Mat_Type = m.Mat_Type };

  return materials;
 }
nWorx
@nWorx it didnt work...
Pandiya Chendur
@nWorx i got the error `Cannot initialize type 'CrMVC.Models.Material' with a collection initializer because it does not implement 'System.Collections.IEnumerable'`
Pandiya Chendur
@nWorx Error `CrMVC.Models.Material does not contain a definition for ID,Name,Type`
Pandiya Chendur
Try changing the return type from IQueryable to IEnumerable.
Bermo
@Bermo still the same error `CrMVC.Models.Material does not contain a definition for ID,Name,Type`
Pandiya Chendur
@Bermo look at my edit in the question...
Pandiya Chendur
@pandiya i don't have any information about you material classjust replace id, name and type with the appropriate properties - i have updated the code....
nWorx
A: 

To obtain the same result-set as your SQL try:

    public class MatertialSet
    {
        public int Mat_id  { get; set; }
        public string Mat_name { get; set; }
        public string Measurement { get; set; }
        public string Description { get; set; }
    }

    public static IQueryable<MatertialSet> FindAllMaterials()
    {
        var materials = from m in db.Materials
                        join Mt in db.MeasurementTypes on m.MeasurementTypeId equals Mt.Id
                        select new MatertialSet
                        {
                            Mat_id = m.Mat_Id,
                            Mat_name = m.Mat_Name,
                            Description = Mt.Name,
                            Measurement = m.Mat_Type
                        };
        return materials.AsQueryable();
    }
Nicholas Murray