views:

49

answers:

2

I have been doing this:

        public List<Role> GetRoles()
    {
        List<Role> result = new List<Role>();

        foreach (var r in Db.tblRoles)
        {
            result.Add(new Role()
            {
                Description = r.d,
                Id = r.Id,
                Responsibility = r.Responsibility
            });

        }
        return result;
    }

I have a lot of table that map 1:1 with my object model, is there a better way to get my table data into my om?

+2  A: 

Much easier using the Select() and ToList() extension methods.

 public List<Role> GetRoles()
 {
      return Db.tblRoles
               .Select( r => new Role
                {
                     Description = r.d,
                     Id = r.Id,
                     Responsibility = r.Responsibility
                })
               .ToList();
 }

Or you could simply rename tblRoles to be Roles in the designer as well as rename the properties -- if you are ok with treating your LINQ entities as your business entities -- and simply do:

 public List<role> GetRoles()
 {
       return Db.Roles.ToList();
 }

The latter is what I typically do, providing my business logic in a separate partial class implementation of the entity using the partial method hooks provided by the designer-generated code.

tvanfosson
+1  A: 

You could also consider using LINQ to Entities. http://msdn.microsoft.com/en-us/library/cc161164%28loband%29.aspx#%5FToc188851309

Jim Lamb