none
How to convert from IEnumerable to List<T>

    Question

  • Hi
    I have a WCF service that exposes methods which returns DataContracts and Lists with DataContracts. Access to my SQL Server is done via Entity Framework. So, I have this service method implementation:

    public List<User> GetAllUsers()
     {
        var context = new EFEntities.DataEntities();
        var allUsers = from users in context.User select users;
        List<User> result = new List<User>();
    
        foreach (var user in allUsers)        
         result.Add(new User()
         {
            ID = user.ID,
            Name = user.UserName
          });
        return result;
     }
    

    This works very well. But I would like to do this in a more generic way because if the model changes or the datacontract needs to be changed I also have to edit all the code of this kind. What is best practice here? Reflection?

    The case is: Convert a Entity Framework entity to a WCF data contract. Or as for this example: from IQueryable to List<User>/List<T>.

    Any suggestion or references to patterns or best practices?

     

    Tuesday, February 01, 2011 1:18 PM

Answers

  • Hello

     

    This should work for u

    public List<User> GetAllUsers()
     {
     var context = new EFEntities.DataEntities();
     var allUsers = from g in context.User select new User{ Id = g.Field<int>("Id"), Name = g.Field<string>("Name") };
     List<User> result = new List<User>();
    
     
    Just Add this code
    result=allusers.ToList<User>(); //Now ur result will contain user collections


    return result;
    }


     


    Regards TurbulentGeek "
    Mark as answer if it helped you..."
    ;
    Tuesday, February 01, 2011 6:04 PM

All replies

  • Simple:

     

    public List<User> GetAllUsers()
    {
    	using ( var context = new EFEntities.DataEntities() )
    	{
    		return context.Users.ToList();
    	}
    }
    
    

     

    Tuesday, February 01, 2011 5:34 PM
  • Hello

     

    This should work for u

    public List<User> GetAllUsers()
     {
     var context = new EFEntities.DataEntities();
     var allUsers = from g in context.User select new User{ Id = g.Field<int>("Id"), Name = g.Field<string>("Name") };
     List<User> result = new List<User>();
    
     
    Just Add this code
    result=allusers.ToList<User>(); //Now ur result will contain user collections


    return result;
    }


     


    Regards TurbulentGeek "
    Mark as answer if it helped you..."
    ;
    Tuesday, February 01, 2011 6:04 PM