Is it possible to run native sql with entity framework?

后端 未结 7 1336
北海茫月
北海茫月 2020-11-28 06:12

I am trying to search an XML field within a table, This is not supported with EF.

Without using pure Ado.net is possible to have native SQL support with EF?

7条回答
  •  难免孤独
    2020-11-28 07:11

    For Entity Framework 5 use context.Database.SqlQuery.

    And for Entity Framework 4 use context.ExecuteStoreQuery the following code:

     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(sequenceMaxQuery).FirstOrDefault();
    
            string buyerSequenceNumber = string.Empty;
    
            if (sequenceQueryResult != null)
            {
                buyerSequenceNumber = sequenceQueryResult.ToString();
            }
    
            return buyerSequenceNumber;
        }
    

    To return a List use the following code:

     public List 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 + "' )";
    
    
        return context.Database.SqlQuery(panelSerialByLocationAndStockQuery).ToList();
    
    
    }
    

提交回复
热议问题