【发布时间】:2017-06-14 12:36:14
【问题描述】:
我想填充下面的实体模型:
public class MyModel
{
public Abc Abc { get; set; }
public Def Def { get; set; }
public List<Ghi> Ghi { get; set; }
}
public class Abc
{
[Key]
public int ID { get; set; }
public string SomeString { get; set; }
}
public class Def
{
[Key]
public int ID { get; set; }
public string OtherString { get; set; }
}
public class Ghi
{
[Key]
public int ID { get; set; }
public int DefID { get; set; }
public string ThirdString { get; set; }
}
使用 EF 的数据和一些原始 SQL 查询:
using (var ctx = new ApplicationDbContext())
{
var abc = ctx.Database.SqlQuery<Abc>(@"SELECT Abc.* FROM XY INNER JOIN Abc ON XY.AbcID = Abc.ID").ToList();
var def = ctx.Database.SqlQuery<Def>(@"SELECT Def.* FROM XY INNER JOIN Def ON XY.DefID = Def.ID").ToList();
var ghi = ctx.Database.SqlQuery<Ghi>(@"SELECT Ghi.* FROM XY INNER JOIN Def ON XY.DefID = Def.ID INNER JOIN Ghi ON Def.ID = Ghi.DefID").ToList();
}
但我不能这样做:
var myModel = new MyModel();
myModel.Abc = abc;
myModel.Def = Def;
myModel.Ghi = Ghi;
因为它会给我带来诸如
之类的错误不能隐式转换类型 'System.Collections.Generic.List' 到 'MyProject.Models.Abc'
所以,问题是:
1) 如何将列表转换为模型,或者更好地使用原始 SQL 直接填充模型而不是列表?
2) 我知道 LinQ 可以用更少的代码让事情变得更简单......我如何使用 LinQ 做到这一点?
【问题讨论】:
标签: entity-framework linq linq-to-entities rawsql entity-model