Lui*_*cia 8 c# ado.net entity-framework entity-framework-4
我需要执行一个自定义查询,它将保存在数据库的某个地方,我需要它返回数据表或数据集并将其绑定到gridview,它将自动生成列为true.
我的所有数据访问层都与实体框架完美配合,但对于某些特定场景,我需要这样做,我想知道是否应该将ado.net与实体框架结合起来,或者如果EF能以某种方式实现它
Md.*_*lam 18
对于Entity Framework 5使用
context.Database.SqlQuery
对于Entity Framework 4,请使用以下代码
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;
}
Run Code Online (Sandbox Code Playgroud)
对于Return a List,请使用以下代码
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();
}
Run Code Online (Sandbox Code Playgroud)
Per*_*eru 12
这是另一个维度和更简单的方法.使用您的实体框架获取SQL连接上下文:
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);
}
Run Code Online (Sandbox Code Playgroud)
我们可以使用DataAdapter或任何其他经典方法使用EF连接执行查询.
当我们动态地执行某些操作以及无法映射到实体时,这将非常有用.例如,我们可以在DataTable中获取内容.
上面的语法适用于EF 5.0.
如果您的目标是返回ADO.NET结构(DataTable或DataSet),那么只需使用经典的ADO.NET.您会发现比尝试将数据绑定到实体集然后自己填充DataTable或DataSet更容易.
但是,如果您真的真的有兴趣通过EntityFramework运行自定义查询,请查看ExecuteQuery.它允许您执行SQL查询并将结果映射回模型中的实体.然后,您将获取IEnumerable结果并将其映射到DataTable或DataSet.因此,我原来的回答是"只需用优质的ADO.NET方法做到这一点."