Reputation: 493
I am new to LINQ and Entity Framework, so far I have only been able to perform relatively simple data queries. I have just begun querying data and storing the results in a class using code such as:
public class myData
{
public string name { get; set; }
public string id {get; set;}
}
var data = (from t1 in MyContext.Table1
from t2 in MyContext.Table2
where t1.Id == "1"
select new myData
{
name = t1.Name,
id = t2.id
}).FirstOrDefault();
Is it possible to also grab data that follows many-to-one relationships? For instance, if have many "datavalues" stored using t1.Id can query this data at the same time?
e.g.
public class myData
{
public string name { get; set; }
public string id {get; set;}
public List<double> data {get; set;}
}
var data = (from t1 in MyContext.Table1
from t2 in MyContext.Table2
where t1.Id == "1"
select new myData
{
name = t1.Name,
id = t2.id
data = t2.datavalues <== This obviously gives a conversion error
}).FirstOrDefault();
It seems like there should be a reasonable way to solve this, but I haven't been able to find anything.
Any help is greatly appreciated!
Upvotes: 0
Views: 2250
Reputation: 203829
What you want to do is to Join
the tables:
var query = from t1 in MyContext.Table1
join t2 in MyContext.Table2
on t1.Id == t2.Id into t2Values
select new myData
{
name = t1.Name,
id = t1.id,
data = t2Values.Select(t2 => t2.SomeField),
};
Upvotes: 1