Search code examples
entity-frameworklinqlinq-to-entitiesrawsqlentity-model

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


I want to populate the entity model below:

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; }
}

With data using EF & some raw SQL queries:

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();
}

But I cannot do it like this:

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

As it would throw me errors such as

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

So, the questions are:

1) How can I convert a List to a Model or better directly populate a Model instead of a List using raw SQL?

2) I know LinQ can make things easier with less code to write... how can I do it with LinQ?


Solution

  • Your error is self explainary you should write it like this:

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

    You trying to put collection that your get with .ToList() extenstion method to property that define as single model.