如何使用 EF 原始 SQL 查询 and/or LinQ 填充实体模型?

How to populate an entity model using EF raw SQL queries and/or LinQ?

我想填充下面的实体模型:

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;

因为它会抛出诸如

之类的错误

Cannot implicitly convert type 'System.Collections.Generic.List' to 'MyProject.Models.Abc'

所以,问题是:

1) 如何将列表转换为模型或更好地使用原始 SQL 直接填充模型而不是列表?

2) 我知道 LinQ 可以用更少的代码让事情变得更简单...我如何使用 LinQ 做到这一点?

你的错误是不言自明的,你应该这样写:

var myModel = new MyModel();
myModel.Abc = abc.FirstOrDefault();
myModel.Def = Def.FirstOrDefault();
myModel.Ghi = Ghi;

您试图将使用 .ToList() 扩展方法获得的集合放入定义为单一模型的 属性。

尝试代码:

var myModel = new MyModel();
using (var ctx = new ApplicationDbContext())
{
  myModel.ABC= (from p in ctx.XYZ
               join q in ctx.Abc on p.AbcId equals q.Id
               select q).FirstOrDefault();
 var result= (from p in ctx.XYZ
               join q in ctx.Def on p.DefId equals q.Id
               select q).ToList();
 myModel.DEF=result.FirstOrDefault();
 myModel.GHI=( from p in result
                join q in ctx.Ghi on p.Id equals q.DefId
                select q).ToList();

}