0 0 0 0


Sorry I'm new to LINQ and Entity framework.

When a linq query fetches a whole Entity, how can i return the result as an object type? I mean not just a field but also to return all the fields of that specific record, as one entity.

For example a Staff table in sql. To return a staff object entity.

if i write Linq code like this:

var db= (from c in context.Staff
                          where == sId
                          select new { s.sId,s.staffNo,,s.surname,s.image});
return db; ---> here 

Gives an error because i want to return result as Staff object.

How can it return as a table column object?

Thank you

Best Answer:

As per your comments, you need a single object returned from your method.

To return a single Item you have following options.

  • First: Returns first item from the collection, if there are no matching items then an exception would be thrown.
  • FirstOrDefault: Works same like First except it would return null if there are no matching records.
  • Single: Returns only one item from the list, It will throw exception if the collection contains more than one item or the collection is empty. A possible usage is when querying against primary key. Only one record should be returned. Exceptional case should be when there are more than one record.
  • SingleOrDefault: Works on the same principal as Single except it would return null if the collection is empty.
  • All these methods can be added at the end of your query syntax or could receive a predicate. Like:

    var db=  (from c in context.Staff
             where == sId
             select c).FirstOrDefault();


    var db = context.Staff.FirstOrDefault(c=> == sId);

    If your field id is a primary key then use SingleOrDefault.

    (Old Answer

    If you are trying to return particular columns from a table, then you can't project your result to your class Staff since that is generated through the framework.

    You have two options. First create another class with properties same as your result set and return its object.

    Or instead of selecting specific columns, select all columns and then return Staff type object.

    var db=  from c in context.Staff
             where == sId
             select c;
    return db;

    If you want to create an other class lets say PartialStaff then you can do:

    var db=  from c in context.Staff
             where == sId
             select new  PartialStaff
                   Id = s.sId,
                   // of the properties

    But then your method return type should be PartialStaff type collection.

    Copyright © 2011 Dowemo All rights reserved.    Creative Commons   AboutUs