I have a linq to sql class with several table bound properties, but I want to add another that is computed from a more complicated query.
Is there a way to add a property that contains custom SQL code while still maintaining efficiency?
public class Region
{
string Name {get ;set;}
DateTime Founding {get; set;}
int CivilWarCasualties
{
get
{
// Scalar SQL code that returns an int
}
}
}
This is how I'm currently doing it (Please ignore the schema and I made it up on the fly). There are not enough one-to-one relationships to do this without doing joins and that obviously makes it more complicated. I use this big join in a bunch of places and I want to simplify it:
using (Context db = new Context())
{
var q = (from r in db.GetTable<Region>()
join b in db.GetTable<Battles>() join s.ID equals b.RegionID
join s in db.GetTable<Soldier>() join s.LastBattleID equals b.ID
join p in db.GetTable<Person>() join p.ID equals s.PersonID
where !p.IsAlive
select new {r, p})
.GroupBy(x => x.Name)
.Select(x=> new {x.Key.r.Name, x.Where(y => y.Key = x.Key).Count());
}
This is how I want to do it:
using (Context db = new Context())
{
var q = (from r in db.GetTable<Region>()
select new {r.Name, r.CivilWarCasualties})
}
I basically want to manually write the SQL code for that big complicated join above once (that I probably didn't get right because I'm making it up as I go as an example).
I'm trying to avoid the "no translation to SQL" error that happens if I try and do a property in C#. I'm also open to other ideas.