We decided to use Linq To SQL for our Data Layer on our most recent project. We have a functional solution, that so far has handled everything we have thrown at it, with one major problem. We have to code the same method over and over again to retrieve just slightly different result sets from our database.
As an example:
public List<TeamBE> GetTeamsBySolutionID(Guid SolutionID)
{
List<TeamBE> teams = new List<TeamBE>();
Esadmin db = new Esadmin(_connectionString);
var qry = (from teamsTable in db.Teams
join solutionsTable in db.Solutions on teamsTable.SolutionID equals solutionsTable.SolutionID
where teamsTable.SolutionID == SolutionID
select new { teamsTable, solutionsTable.SolutionName });
foreach (var result in qry)
{
TeamBE team = new TeamBE();
team.TeamID = result.teamsTable.TeamID;
team.Description = result.teamsTable.Description;
team.Status = result.teamsTable.Status;
team.LastModified = result.teamsTable.LastModified;
team.SolutionID = result.teamsTable.SolutionID;
team.SolutionName = result.SolutionName;
team.Name = result.teamsTable.Name;
team.LocationLevel = result.teamsTable.LocationLevel;
team.AORDriven = result.teamsTable.AoRDriven;
team.CriteriaID = result.teamsTable.CriteriaID ?? Guid.Empty;
teams.Add(team);
}
return teams;
}
public TeamBE GetTeamByID(Guid TeamID)
{
Esadmin db = new Esadmin(_connectionString);
TeamBE team = new TeamBE();
var qry = (from teamsTable in db.Teams
join solutionsTable in db.Solutions on teamsTable.SolutionID equals solutionsTable.SolutionID
where teamsTable.TeamID == TeamID
select new { teamsTable, solutionsTable.SolutionName }).Single();
team.TeamID = qry.teamsTable.TeamID;
team.Description = qry.teamsTable.Description;
team.Status = qry.teamsTable.Status;
team.LastModified = qry.teamsTable.LastModified;
team.SolutionID = qry.teamsTable.SolutionID;
team.SolutionName = qry.SolutionName;
team.Name = qry.teamsTable.Name;
team.LocationLevel = qry.teamsTable.LocationLevel;
team.AORDriven = qry.teamsTable.AoRDriven;
team.CriteriaID = qry.teamsTable.CriteriaID ?? Guid.Empty;
return team;
}
And on and on ad nauseum.
Is there is a way to pass Linq results as a parameter to a function, so I can place my object mappings in one function, and not repeat myself so much?
I took a quick stab at it. Probably doesn’t compile (Especially the “from teamsTalbe in teams), but the idea is you can factor out something that returns an IQueryable<>. You’re IQueryable returns an anonymous type though, which wouldn’t work. So you may need to create an explicit type to use in place of ‘select new { teamsTable, solutionsTable.SolutionName }’