gpt4 book ai didi

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

转载 作者:IT王子 更新时间:2023-10-29 04:26:54 30 4
gpt4 key购买 nike

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

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/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com