tags:

views:

78

answers:

1

I've my Model something maybe like this :

    public class Person
    {
        public virtual Guid ID { get; set; }
        public virtual string FirstName { get; set; }
        public virtual string LastName { get; set; }
        //this LazyList takes IQueryable<T> in constructor
        public virtual LazyList<Role> Roles { get; set; }

        //this method to convert the object that comes from EF to my own model
        public static Person FromData(DBPerson dbPerson)
        {
            if (dbPerson != null)
                return new Person
                {
                    ID = dbPerson.ID,
                    FirstName = dbPerson.FirstName,
                    LastName = dbPerson.LastName,
                };

            return null;
        }
     }

Then in my Repository I've method to get all persons but i need it to give to the LazyList<Role> property result from other private method "getRoles". My repository looks like this:

        public IQueryable<Person> GetPersons()
        {
            var list = from dbPerson in context.Persons 
                       select Person.FromData(dbPerson);
       // Here is the problem :(
            return list;
        }

        private LazyList<Role> getRoles(GUID userID)
        {
            var list = from role in db.Roles
                       where role.UserID == userID
                       select role.ToModel();

            return new LazyList<Role>(list);
        }

I want something here to tell this Linq statement that i want Person.Roles to get its value from "getRoles" method

Maybe someone will tell me to put the logic of converting the dbPerson to my Person in the repository and then put something like this :

        public IQueryable<Person> GetPersons()
        {
            var list = from dbPerson in context.Persons 
                       select new Person{
                    ID = dbPerson.ID,
                    FirstName = dbPerson.FirstName,
                    LastName = dbPerson.LastName,
                    Roles = getRoles(dbPerson.ID)};
        }

OK that will work but i really need to put the logic of converting dbPerson to my model in separate method because i'll sue it many times in my solution.

So how to do that ?

+1  A: 

What about a separate method to make the conversion? This way you can reuse it.

public  Person ToPerson(dbPerson row, bool getDetails)
{
     Person result = new Person{
                                ID = row.ID,
                                FirstName = row.FirstName,
                                LastName = row.LastName};
     if(getDetails)
     {
         result.Roles = getRoles(row.ID)};
     }

     return result;
}
djacosta
This kinda tricking but i need to make my convert method static.and another thing this would make me set this method in repository but i want to use it in many places. Thank you anyway :)
Wahid Bitar