[英]How to create a temporary table and use it in the same connection with Entity Framework?
I am trying to execute a three raw queries with Entity Framework.我正在尝试使用实体框架执行三个原始查询。
The first query will basically create a temporary table.第一个查询基本上会创建一个临时表。 The second query will add an index on the temporary table.
第二个查询将在临时表上添加索引。 Finally, the second query will join to the temporary table to other table to get a final dataset.
最后,第二个查询会将临时表连接到其他表以获得最终数据集。
But every time I run my code, get the following error但是每次运行我的代码时,都会出现以下错误
invalid
#allRecords
object.无效的
#allRecords
对象。
Here is what I have done这是我所做的
using (BaseContextdb = new BaseContext())
{
using (var dbContextTransaction = db.Database.BeginTransaction())
{
try
{
db.Database.ExecuteSqlCommand("SELECT col1, col2, col3 " +
"INTO #allRecords " +
"FROM someTable " +
"WHERE col5 = 'blab' " +
"CREATE INDEX d ON #allRecords(col1, col2); ");
var results = db.Database.SqlQuery<ResuleModel>(this.GetQuery()).ToList();
db.SaveChanges();
dbContextTransaction.Commit();
}
catch (Exception)
{
dbContextTransaction.Rollback();
}
}
}
how can I correctly create temporary table with Entity Framework?如何使用实体框架正确创建临时表?
UPDATED更新
Here is the query that is returned by this.GetQuery()
这是
this.GetQuery()
返回的查询
SELECT b.*, c.*
FROM b
INNER JOIN #allRecords AS a ON a.col1 = v.col1 AND a.col2 = b.col2
INNER JOIN c ON c.Id= b.Id
...
...
...
Entity Framework doesn't work well with temporary tables.实体框架不适用于临时表。
Instead, you might want to look at Dapper .相反,您可能想要查看Dapper 。 It is much cleaner;
干净多了; besides, you can use EF and Dapper in same project side-by-side.
此外,您可以在同一个项目中并排使用 EF 和 Dapper。 For example,
例如,
using (IDbConnection conn = new SqlConnection(DataBaseConnectionString))
{
conn.Open();
// If you want transaction, place it inside the query.
var entities = conn.Query<ResuleModel>(@"SELECT col1, col2, col3 ...");
result = entities.ToList();
}
FYI: Make sure you execute the query in SSMS before using it in Dapper.仅供参考:在 Dapper 中使用之前,请确保在 SSMS 中执行查询。
Need to Open
a new connection before you create, insert or query the temp table.在创建、插入或查询临时表之前需要
Open
一个新连接。
The opened connection will not be automatically closed until context disposal.在上下文处理之前,打开的连接不会自动关闭。
db.Database.Connection.Open();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.