C# 如何在实体框架中访问 c​​ontext.Database.SqlQuery?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11792018/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 19:17:00  来源:igfitidea点击:

How to access context.Database.SqlQuery in Entity Framework?

c#sqlentity-framework

提问by Funky

I am trying to follow this tutorial:

我正在尝试按照本教程进行操作:

http://blogs.msdn.com/b/diego/archive/2012/01/10/how-to-execute-stored-procedures-sqlquery-in-the-dbcontext-api.aspx

http://blogs.msdn.com/b/diego/archive/2012/01/10/how-to-execute-stored-procedures-sqlquery-in-the-dbcontext-api.aspx

but can't seem to to access this method, it will not show up in intelli-sense

但似乎无法访问此方法,它不会以智能方式显示

context.Database.SqlQuery

I am using the following code but can't seem to access the SqlQuery method:

我正在使用以下代码,但似乎无法访问 SqlQuery 方法:

using(Entities db = new Entities())
{    
}

回答by Not loved

The method you have described is valid for executing SQL vs a DbContextversion of EF. (DbContextis used for Code First and is also available for model first but you need to do a little setup). However in your example it should be the following.

您描述的方法适用于执行 SQL 与DbContextEF 版本。(DbContext用于代码优先,也可用于模型优先,但您需要进行一些设置)。但是,在您的示例中,它应该如下所示。

using(Entities db = new Entities())
{   
    db.Database.SqlQuery(....);
}

If you are using OOB model first (ie edmx), you are probably using an ObjectContext, in which case you will need to perform the following:

如果您首先使用 OOB 模型(即 edmx),则您可能使用的是ObjectContext,在这种情况下,您需要执行以下操作:

using(Entities db = new Entities())
{   
    db.ExecuteStoreQuery<ReturnType>("...");
}

See: http://blogs.microsoft.co.il/blogs/gilf/archive/2009/11/25/execute-t-sql-statements-in-entity-framework-4.aspx

请参阅:http: //blogs.microsoft.co.il/blogs/gilf/archive/2009/11/25/execute-t-sql-statements-in-entity-framework-4.aspx

回答by Thulasiram

return context.Database.SqlQuery<myEntityType>("mySpName {0}, {1}, {2}",
new object[] { param1, param2, param3 });

//Or

//或者

using(var context = new MyDataContext())
{
return context.Database.SqlQuery<myEntityType>("mySpName {0}, {1}, {2}",
new object[] { param1, param2, param3 }).ToList();
}

//Or

//或者

using(var context = new MyDataContext())
{
object[] parameters =  { param1, param2, param3 };

return context.Database.SqlQuery<myEntityType>("mySpName {0}, {1}, {2}",
parameters).ToList();
}

//Or

//或者

using(var context = new MyDataContext())
{  
return context.Database.SqlQuery<myEntityType>("mySpName {0}, {1}, {2}",
param1, param2, param3).ToList();
}