How to send regular embedded SQL to entity structure

Now, do not do it all uncomfortable. This is only for a very specific situation. So instead of asking why I would like to send a SQL string string through EF, let me just try to focus on the subject of how.

Do I need to do an old-fashioned route using plain old ADO.NET or EF provides me with a way to execute direct sql select / nonquery?

Thanks in advance.

+3
source share
2 answers

Have you researched Entity SQL ?

Entity Framework Q & A :

string city = "London";
using (Entities entities = new Entities()) 
{
  ObjectQuery<Customers> query = entities.CreateQuery<Customers>(
    "SELECT VALUE c FROM Customers AS c WHERE c.Address.City = @city",
    new ObjectParameter("city", city)
  );

  foreach (Customers c in query)
    Console.WriteLine(c.CompanyName);
}

Entity SQL DML, , Entity SQL Object

+3

ObjectQuery, , context.Database.SqlQuery<> SqlParameter.

:

var searchId = new Guid("16144A52-A092-4876-9C55-A0AD0109F08A");

var sqlparam = new SqlParameter("sid", searchId);

using (var context = new Entities())
{
    var sql = @"SELECT t1.Name, t2.ChildName
        FROM dbo.Table1 as t1 
        INNER JOIN dbo.Table1 as t2 
            ON t1.Id = t2.ParentId 
        WHERE t1.Id = @sid"

    var result = context.Database.SqlQuery<Combined>(sql, sqlparam);

    foreach(var r in result)
    {
         Console.WriteLine(r.Name + r.ChildName)
    }
}


public class Combined
{
    public string Name { get; set; }
    public string ChildName { get; set; }
}
+1

Source: https://habr.com/ru/post/1790876/


All Articles