c# - ExecuteSqlCommand 与 SqlQuery 有什么区别?什么时候做数据库访问?

标签 c# asp.net entity-framework sql-server-2012 entity-framework-6

我有一些关于如何从我的数据库访问数据的建议:

var allMyIds
    = context.Database.ExecuteSqlCommand("select id from AspNetUserLogins");

var allMyIds
    = context.Database.SqlQuery<string>("select id from AspNetUserLogins");

有人能解释一下它们之间的区别吗?

最佳答案

SqlQuery 方法允许您从数据库返回实体。 ExecuteSqlCommand 只是运行命令并从数据库返回状态代码。

More here

SqlQuery(强调我的)

Creates a raw SQL query that will return elements of the given type. The type can be any type that has properties that match the names of the columns returned from the query, or can be a simple primitive type. The type does not have to be an entity type. The results of this query are never tracked by the context even if the type of object returned is an entity type. Use the SqlQuery method to return entities that are tracked by the context. As with any API that accepts SQL it is important to parameterize any user input to protect against a SQL injection attack. You can include parameter place holders in the SQL query string and then supply parameter values as additional arguments. Any parameter values you supply will automatically be converted to a DbParameter. context.Database.SqlQuery(typeof(Post), "SELECT * FROM dbo.Posts WHERE Author = @p0", userSuppliedAuthor); Alternatively, you can also construct a DbParameter and supply it to SqlQuery. This allows you to use named parameters in the SQL query string. context.Database.SqlQuery(typeof(Post), "SELECT * FROM dbo.Posts WHERE Author = @author", new SqlParameter("@author", userSuppliedAuthor));

ExecuteSqlCommand 返回类型:int

Executes the given DDL/DML command against the database. As with any API that accepts SQL it is important to parameterize any user input to protect against a SQL injection attack. You can include parameter place holders in the SQL query string and then supply parameter values as additional arguments. Any parameter values you supply will automatically be converted to a DbParameter. context.Database.ExecuteSqlCommand("UPDATE dbo.Posts SET Rating = 5 WHERE Author = @p0", userSuppliedAuthor); Alternatively, you can also construct a DbParameter and supply it to SqlQuery. This allows you to use named parameters in the SQL query string. context.Database.ExecuteSqlCommand("UPDATE dbo.Posts SET Rating = 5 WHERE Author = @author", new SqlParameter("@author", userSuppliedAuthor));

关于c# - ExecuteSqlCommand 与 SqlQuery 有什么区别?什么时候做数据库访问?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24248307/

相关文章:

c# - 如何在构建后自动实例化单例?

entity-framework - 如何从独立应用程序创建/使用 Lightswitch 域模型 (EF)?

c# - 在辅助类中使用静态方法与非静态方法

c# - 如何在 Azure 移动应用上托管 API

javascript - jQuery.validate 可能破坏了 Facebox 弹出窗口

c# - View 会降低 LINQ 查询性能吗?

c# - 为什么使用存储库模式或者请向我解释一下?

c# - 什么是.Net中的序列化

c# - 如何升级到 C# 5?

c# - 为什么我的 cookie 没有设置?