我是LINQ和Entity Framework的新手,到目前为止我只能执行相对简单的数据查询。我刚刚开始查询数据并使用以下代码将结果存储在类中:
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();
是否有可能获取遵循多对一关系的数据?例如,如果使用t1存储了许多“数据值”,我可以同时查询这些数据吗?
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();
似乎应该有一个合理的方法来解决这个问题,但我找不到任何东西。
非常感谢任何帮助!
答案 0 :(得分:1)
您要做的是Join
表:
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),
};