best way to map linq2sql objects to entities
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?
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.
You could also consider using LINQ to Entities. http://msdn.microsoft.com/en-us/library/cc161164(loband).aspx#_Toc188851309
精彩评论