Generic Linq Query With an Interface
I have several database tables that implement an interface, IValue; this is obviously an example, but I can't alter the database design:
public partial class Table1 : //Linq Table
{
*int ID {get; set;}
*string Name {get; set;}
}
public partial class Table2 : //Linq Table
{
*int ID {get; set;}
*int Height {get; set;}
*int Width {get; set;}
}
public partial class Table1 : ValueCollection<Table1>, IValue
{
double Value {get; set;}
}
public partial class Table2 : ValueCollection<Table2>, IValue
{
double Value {get; set;}
}
The tables physically contain the properties denoted with the asterkisk. I can then run a query that selects the relevant data from either table:
class ValueCollection<T> where T : IValue
{
IQueryable<T> Collection
{
using (Database db = new Database())
{
var results = from t in db.GetTable<T>
select t;
//results = {{ID = 1, Name = "A", Value = 0},
// {ID = 2, Name = "B", Value = 0},
// ...}
I then populate the .Value property with a for loop:
for (int i = 0; i < results.Count(); i++)
{
results[i].Value = (from v in db.Values
where v.KeyID = results[i].ID
开发者_如何学编程 select v.Value).First();
}
return results;
}
}
}
I'd like to be able to somehow combine the for loop into the first linq query, but I have no idea how to do it with the interface. The first query selects all the relevant data from the Table1 table, and then the second one populates the .Value property. I can't use the initializer syntax in the linq query because I would then have to hard code the attributes that are in Table1 or Table2.
I'm sort of doing a join, but I'm explicitly returning a type T instead of an anonymous type. Is there perhaps a way to convert this to a join query and then return the result as a Queryable<T>
without explicitly assigning the properties?
Edit: Updated the code per Jon's request.
If I do this, shouldn't results have an ID property?
foreach (var s in Table1.Collection) {Console.WriteLine(s.ID)};
It would be the same thing as doing:
(from t in db.Table1s
select t);
t
will have ID and Name properties and Value will be unassigned.
精彩评论