跟在以下之间有什么区别?
CreateQuery() ExecuteFunction(), ExecuteStoreQuery() and ExecuteStoreCommand()
据我所知,CreateQuery用于实体SQL,其余方法用于sql函数或在DB中定义的存储过程。
根据ObjectContext类元数据,它们如下:
CreateQuery():Creates an System.Data.Objects.ObjectQuery<T> in the current object context by using the specified query string.
Returned -> System.Data.Objects.ObjectQuery<T>
ExecuteFunction(): Executes a stored procedure or function that is defined in the data source and expressed in the conceptual model; discards any results returned from
the function; and returns the number of rows affected by the execution.
Returned -> The number of rows affected.
This has an overloaded version which return -> The entity type of the System.Data.Objects.ObjectResult<T>
ExecuteStoreCommand(): Executes an arbitrary command directly against the data source using the existing connection.
Return -> The number of rows affected.
ExecuteStoreQuery(): Executes a query directly against the data source that returns a sequence of typed results.
Return -> An enumeration of objects of type TResult.
根据以上信息-
Use ExecuteFunction() if you have added db Function/Stored Procedure in your EDMX & can be used for both insert/update & getting result set.
Use ExecuteStoredCommand() if you have not added db Function/Stored Procedure in your EDMX & can be used to insert/update only.
ExecuteStoreQuery() can do what Executefuction() can do except that you no need to add your db Function/Stored Procedure in EDMX & IEnumerable can be used as return type.
如果我错了,请纠正我。任何进一步的信息将不胜感激。
最佳答案
以下内容与非常相似:CreateQuery :
var id = 42;
using(var ctx = new Entities()){
var query = ctx.Companies.Where(o=>o.Id==id);
var result = query.First();
}
在我调用First()之前,查询只是一个查询。什么都没有发送到数据库。仅当请求数据时,查询才会被执行并检索数据。
编写lambda很容易,但是可以说您可以牺牲它以获取其他好处。如果EDMX不了解您的数据映射,则您基本上只能使用 ExecuteStoreQuery 。前任。您已经手动创建了映射。
var queryString = "SELECT ... FROM " + tableName;
var table = context.ExecuteStoreQuery<ResultTableTemplate>(queryString );
为您的应用程序编写代码很好,但是有时数据库的生命周期超过了几个用户界面。为了最大程度地减少需要完成的工作量,您可以将某些功能(如果不是全部功能)存储在数据库中。它们可以主要作为函数或过程存储在此处。
ExecuteFunction仅用于函数导入。函数是计算值,不能对SQL Server进行永久的环境更改(即,不允许INSERT或UPDATE语句)。要在C#中调用自定义函数
Select Today()
:var date = ctx.ExecuteFunction<DateTime>("Today").First();
Entity Framework 支持三种加载相关数据的方式-预先加载,延迟加载和显式加载。默认情况下,它是延迟加载,这就是为什么您使用 .First()/。FirstOrDefault/.ToList/... 看到我的原因,以获取有关如何根据需要加载数据的更多信息,您可以看看Loading Related Entities。
过程类似于数据库批处理脚本。如果您使用数据库优先设计,那么大多数业务逻辑很可能将存储在过程中。您可以像这样在C#中调用它们:
var cmdText = "[DoStuff] @Name = @name_param, @Age = @age_param";
var @params = new[]{
new SqlParameter("name_param", "Josh"),
new SqlParameter("age_param", 45)
};
ObjectContext.ExecuteStoreQuery<MyObject>(cmdText, @params);
奖励:
您想做的一件事是call a stored procedure that accepts a table value parameter。
关于c# - Entity Framework -CreateQuery VS ExecuteFunction VS ExecuteStoreQuery VS ExecuteStoreCommand,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22368794/