Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

execute custom sql with entity framework?

I need to execute a customquery which wil be saved somewhere in the database and I need it to return in a datatable, or dataset and bind it to a gridview which will have autogenerate columns to true.

All my Data access layer works perfect with entity framework, but for some specific scenario I need to do this and I wonder if I should combine ado.net with entity framework, or if EF can do it somehow

like image 628
Luis Valencia Avatar asked Jun 05 '12 13:06

Luis Valencia


People also ask

Can we use SQL query in Entity Framework?

Entity Framework allows you to execute raw SQL queries for the underlying relational database.

How do I run a raw SQL query using DbContext?

From the DbContext 's database object, create the Db command. Then, assign all the required parameters to the command object like the SQL, Command Type, SQL parameters, use existing DB transition, and optional command timeout to the command. Finally, calling ExecuteNonQuery() to execute the raw SQL query.

How use raw SQL query in Entity Framework Core?

The FromSql method allows parameterized queries using string interpolation syntax in C#, as shown below. string name = "Bill"; var context = new SchoolContext(); var students = context. Students . FromSql($"Select * from Students where Name = '{name}'") .

Does Entity Framework use parameterized queries?

EF builds and executes a parameterized query in the database if the LINQ-to-Entities query uses parameters, such as below.


2 Answers

For Entity Framework 5 use

context.Database.SqlQuery


And For Entity Framework 4 use the following code

context.ExecuteStoreQuery


 public string BuyerSequenceNumberMax(int buyerId)
    {
        string sequenceMaxQuery = "SELECT TOP(1) btitosal.BuyerSequenceNumber FROM BuyerTakenItemToSale btitosal " +
                                  "WHERE btitosal.BuyerID =  " + buyerId +
                                  "ORDER BY  CONVERT(INT,SUBSTRING(btitosal.BuyerSequenceNumber,7, LEN(btitosal.BuyerSequenceNumber))) DESC";

        var sequenceQueryResult = context.Database.SqlQuery<string>(sequenceMaxQuery).FirstOrDefault();

        string buyerSequenceNumber = string.Empty;

        if (sequenceQueryResult != null)
        {
            buyerSequenceNumber = sequenceQueryResult.ToString();
        }

        return buyerSequenceNumber;
    }

For Return a List use the following Code

 public List<PanelSerialList> PanelSerialByLocationAndStock(string locationCode, byte storeLocation, string itemCategory, string itemCapacity, byte agreementType, string packageCode)
 {
       string panelSerialByLocationAndStockQuery = "SELECT isws.ItemSerialNo,  im.ItemModel " +
        "FROM Inv_ItemMaster im   " +
        "INNER JOIN  " +
        "Inv_ItemStockWithSerialNoByLocation isws  " +
        "   ON im.ItemCode = isws.ItemCode   " +
        "       WHERE isws.LocationCode = '" + locationCode + "' AND  " +
        "   isws.StoreLocation = " + storeLocation + " AND  " +
        "   isws.IsAvailableInStore = 1 AND " +
        "   im.ItemCapacity = '" + itemCapacity + "' AND " +
        "   isws.ItemSerialNo NOT IN ( " +
        "           Select sp.PanelSerialNo From Special_SpecialPackagePriceForResale sp  " +
        "           Where sp.PackageCode = '" + packageCode + "' )";



    context.Database.SqlQuery<PanelSerialList>(panelSerialByLocationAndStockQuery).ToList();


}
like image 115
Md. Nazrul Islam Avatar answered Sep 21 '22 15:09

Md. Nazrul Islam


Here's another dimension and easier approach. Get SQL Connection using your Entity Framework Context:

var connection = (System.Data.SqlClient.SqlConnection) _db.Database.Connection;

if (connection != null && connection.State == ConnectionState.Closed)
{
    connection.Open();
}

var dt = new DataTable();

using (var com = new System.Data.SqlClient.SqlDataAdapter("Select * from Table", connection))
{
    com.Fill(dt);
}

And we can use DataAdapter or any other classic method to execute queries using the EF connection.

This will be very useful when we do something dynamically and when we can't map to a Entity. We can get things in a DataTable for example.

The above Syntax is for EF 5.0.

like image 23
Peru Avatar answered Sep 20 '22 15:09

Peru