是否可以使用实体框架运行本机sql?

use*_*855 65 sql ado.net entity-framework

我正在尝试搜索表中的XML字段,EF不支持此功能.

如果不使用纯Ado.net,可以在EF中使用本机SQL支持吗?

Jus*_*ant 72

对于.NET Framework版本4及更高版本:ObjectContext.ExecuteStoreCommand()如果查询未返回任何结果,请使用,ObjectContext.ExecuteStoreQuery如果查询返回结果,请使用.

对于以前的.NET Framework版本,这里有一个示例说明了要做什么.如果查询返回结果,请根据需要替换ExecuteNonQuery().

static void ExecuteSql(ObjectContext c, string sql)
{
    var entityConnection = (System.Data.EntityClient.EntityConnection)c.Connection;
    DbConnection conn = entityConnection.StoreConnection;
    ConnectionState initialState = conn.State;
    try
    {
        if (initialState != ConnectionState.Open)
            conn.Open();  // open connection if not already open
        using (DbCommand cmd = conn.CreateCommand())
        {
            cmd.CommandText = sql;
            cmd.ExecuteNonQuery();
        }
    }
    finally
    {
        if (initialState != ConnectionState.Open)
            conn.Close(); // only close connection if not initially open
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 这个答案已经过时了.请参阅此文章http://geekswithblogs.net/rgupta/archive/2010/06/23/entity-framework-v4-ndash-tips-and-tricks.aspx.您可以直接从实体框架执行Sql,不需要使用实现实例的**ExecuteStoreCommand**或**ExecuteStoreQuery**所需的包装器. (38认同)
  • 请记住,DbContext不支持这些方法,但有Database.ExecuteSqlCommand()或Database.SqlQuery <T>. (9认同)

Len*_*rri 24

使用Entity Framework 5.0您可以ExecuteSqlCommand用来执行多行/多命令纯SQL语句.这样您就不需要提供任何后备对象来存储返回的值,因为该方法返回一个int(执行命令后数据库返回的结果).

样品:

context.Database.ExecuteSqlCommand(@
"-- Script Date: 10/1/2012 3:34 PM  - Generated by ExportSqlCe version 3.5.2.18
SET IDENTITY_INSERT [Students] ON;

INSERT INTO [Students] ([StudentId],[FirstName],[LastName],[BirthDate],[Address],[Neighborhood],[City],[State],[Phone],[MobilePhone],[Email],[Enrollment],[Gender],[Status]) VALUES (12,N'First Name',N'SecondName',{ts '1988-03-02 00:00:00.000'},N'RUA 19 A, 60',N'MORADA DO VALE',N'BARRA DO PIRAÍ',N'Rio de Janeiro',N'3346-7125',NULL,NULL,{ts '2011-06-04 21:25:26.000'},2,1);

INSERT INTO [Students] ([StudentId],[FirstName],[LastName],[BirthDate],[Address],[Neighborhood],[City],[State],[Phone],[MobilePhone],[Email],[Enrollment],[Gender],[Status]) VALUES (13,N'FirstName',N'LastName',{ts '1976-04-12 00:00:00.000'},N'RUA 201, 2231',N'RECANTO FELIZ',N'BARRA DO PIRAÍ',N'Rio de Janeiro',N'3341-6892',NULL,NULL,{ts '2011-06-04 21:38:38.000'},2,1);
");
Run Code Online (Sandbox Code Playgroud)

有关这方面的更多信息,请查看此处:实体框架代码优先:在数据库创建时执行SQL文件


Md.*_*lam 17

对于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)

要返回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 + "' )";


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


}
Run Code Online (Sandbox Code Playgroud)


And*_*nko 16

从.NET 4开始,您可以使用以下ExecuteStoreQuery方法:

var list = myDBEntities.ExecuteStoreQuery<MyClass>(MyClass.sql);
Run Code Online (Sandbox Code Playgroud)

其中myDBEntities继承自ObjectContext.

class MyClass
{
    /* You can change query to more complicated, e.g. with joins */
    public const string sql = @"select [MyTable].[MyField] from [MyTable]";
    public string MyField { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

请注意,MyTable是真正的表名,而不是EF类.