EF6 alpha Async Await on an Entity Stored Procedure / Function Import? - entity-framework

I'd like to apply the new async await functionality to Stored Procedures / Function Imports imported in my Entity model, but have as yet been unable to with the EF6 alpha.
Is it yet possible in EF6 alpha2 (or the nightly build as of 20211) to call any of the new Async methods on an Entity Function Import (which calls a SQL Stored Procedure) that returns a collection of Complex Type? e.g.
private async Task<IList<Company>> getInfo (string id)
{
using (CustomEntity context = new CustomEntity())
{
var query = await context.customStoredProcedure(id).ToListAsync();
// ".ToListAsync()" method not available on above line
// OR ALTERNATIVELY
var query = await (from c in context.customStoredProcedure(id)
select new Company
{
Ident = c.id,
Name = c.name,
Country = c.country,
Sector = c.sector,
etc. etc....
}).ToListAsync();
// ".ToListAsync()" method or any "...Async" methods also not available this way
return query;
}
}
"ToListAsync", or any of the new async modified methods do not seem to be available to the above Entity Stored Procedure / Function Import; only the standard "ToList" or "AsNumerable" etc methods are available.
I followed this (http://entityframework.codeplex.com/wikipage?title=Updating%20Applications%20to%20use%20EF6) to make sure the code is referencing the new EF6 dlls and not EF5, as well as updated the various using statements. Aside from above, everything builds correctly. (.NET Framework 4.5)
The only time I can see the async methods is if instead of only importing stored procedures from the DB, I also import a table--then when referencing that table via the Entity context as above (context.SomeTable), some of the async methods appear in intellisense.
I'd really like to start using the new async await functionality on multiple Stored Procedures prior to returning data as JSON, but have not been able to get it to work so far.
Am I doing something wrong? Is async functionality not possible on Entity stored procedure / function imports? Thanks for your advice.

Now this is by no means the best solution. I added an extension method so that I could call await on my stored procedures. In the newer releases of EF6.1+ we should see this officially implemented. Until then a dummy extension method does the job.
static async Task<List<T>> ToListAsync<T>(this ObjectResult<T> source)
{
var list = new List<T>();
await Task.Run(() => list.AddRange(source.ToList()));
return list;
}
If you reflect version 6 of EF you will see that ObjectResult<T> actually implements IDbAsyncEnumerable<T>, IDbAsyncEnumerable. And the method for ToListAsync<T>(this IDbAsyncEnumerable<T> source) should be able to wire it up the same as a LINQ query.
Edit
When the ObjectResult is empty null is returned. You could add if (source == null) return new List<T>(); if you want to return an empty List instead of null.

This is an old thread, but I felt I should share. You should use APM then wrap the synchronous calls in a Task.
Example:
//declare the delegate
private delegate MyResult MySPDelegate();
// declare the synchronous method
private MyResult MySP()
{
// do work...
}
Then wrap the synchronous method in a Task:
// wraps the method in a task and returns the task.
public Task<MyResult> MySPAsync()
{
MySPDelegate caller = new MySPDelegate(MySP);
return Task.Factory.FromAsync(caller.BeginInvoke, caller.EndInvoke, null);
}
Call the async method when you want to execute:
var MyResult = await MySPAsync();
You can use up to three (3) parameters in the methods. Best practice is if you use more than three parameters; you should pass in a class.

Related

Entity Framework Core: User Defined SQL Functions

Is it possible to invoke a user-defined SQL function from the query interface in EF Core? For example, the generated SQL would look like
select * from X where dbo.fnCheckThis(X.a, X.B) = 1
In my case, this clause is in addition to other Query() method calls so FromSQL() is not an option.
I just managed this with help from this article (H/T #IvanStoev for his comment on the question).
In your DbContext class:
[DbFunction("my_user_function_name")]
public static bool SatisfiesMyUserFunction(int i)
{
throw new Exception(); // this code doesn't get executed; the call is passed through to the database function
}
Note that the function must be in the DbContext class, even though it is static.
Then create a database migration and define the user function in the script.
Usage:
var query = db.Foos.Where(f => MyDbContext.SatisfiesMyUserFunction(f.FieldValue));

EF deferred execution using SQLquery as input

I am trying to get an entity with EF by having an initial sql as input.
I tried the context.Entities.SQLQuery method but this returns a DBSet when I require an IQueriable.
I learned that I cannot transform DBSet to IQueryable because the first is already a result of data while the second is the container for the results of a "query" (executed yet or not). Correct me if i'm wrong :)
So I thought that when I write the following lambda I get the resulting query:
db.MyTable.Where(x => x.id == "123")
Becomes:
SELECT * FROM myTable WHERE id = '123'
With this I thought if I can set directly my query without needing to set my lambda...
Is that an option?
Or an alternative?
Thanks!
It's a bit unclear what you mean:
I am trying to get an entity with EF having an initial sql as input.
I'd interpret this, as that you have an SQL statement as input of something and you want to get an entity framework entity that would have this statement (whatever having a statement means)? Not understandable!
I learned that I cannot transform DBSet to IQueryable because the
first (the DbSet) is already a result of data while the second (the IQueryable) is the container for the results of a "query"
NOT!
Every DbSet<T> implements IQueryable<T>, meaning that if you have an object of class DbSet<t>, this object implements all functionality of IQueryable<T>. Just using this IQueryable does not execute the query. The query will only be executed once the first element of the sequence if requested.
using (var dbContext = new MyDbcontext())
{
var result = dbContext.MyItems
.Where(item => ...)
.Select(item => new
{
X = item.Property1,
Y = item.Property2,
...
};
Until here, the first element of the sequence is not asked, the query is not performed yet. No communication with the database was needed (except to create the dbContext object)
Only if you use execution functions like ToList(),Count(), First(), Max(), etc, the query is performed.
You can check this, because you get exceptoin if you do these kind of functions after the using block:
Wrong
IQueryable largeItems;
using (var dbContext = new MyDbcontext())
{
largeItems = dbContext.MyItems
.Where(item => item.Size > 1000);
// query not executed yet
}
int nrOfLargeItems = largeItems.Count();
// exception, query executed after dbContext is disposed
correct
int nrOfLargeItems;
using (var dbContext = new MyDbcontext())
{
var largeItems = dbContext.MyItems
.Where(item => item.Size > 1000);
// query not executed yet
nrOfLargeItems = largeItems.Count();
// the query is performed
}
Conclusion: users of a DbSet<T> inside a dbContext can use the DbSet<T> as if it was an IQueryable<T>, the query will not be executed until you perform any function that needs the first element of the query.
This includes complex functions like Join, GroupBy, OrderBy, etc. You can recognize these functions because MSDN add the following to the remarks section
This method is implemented by using deferred execution. The immediate return value is an object that stores all the information that is required to perform the action. The query represented by this method is not executed until the object is enumerated either by calling its GetEnumerator method directly or by using foreach.

Create async methods to load data from database using EF

how does one write an async method that gets data from database, using DbContext and .NET 4.0?
public Task<List<Product>> GetProductsAsync()
{
// Context.Set<Product>().ToList();
}
so we can await somewhere for result of this method
// somewhere
List<Product> products = await repository.GetProductsAsync();
What is important is that I do not want to use thread pool thread for this task, since this is an IO task, and I need to support framework 4.0, and EF6 had added support for async methods only in 4.5, if I am not mistaken.
Not possible, SaveAsync is wrapped with:
#if !NET40
Source: https://github.com/aspnet/EntityFramework6/blob/master/src/EntityFramework/DbContext.cs#L335
Installing Entity Framework 6 is available as a Nuget Package and works also with .NET 4. In EF6, async
DB calls can be done like this example:
public static async Task<List<Customer>> SelectAllAsync()
{
using (var context = new NorthWindEntities())
{
var query = from c in context.Customers
orderby c.CustomerID ascending
select c;
return await query.ToListAsync();
}
}
Here, a DbContext is instantiated in a using block and the query will search the Northwind database for all its customers and order ascending by primary key CustomerID. The method needs to be decorated with async keyword and must return a task of the desired type T, here a list of customers. The result will then be return by using the ToListAsync() method in this case and one must remember to use the await keyword. There are additional Async methods in EF6, such as SaveChangesAsync, SingleOrDefaultAsync and so on. Also, async methods in C# should following this naming conventions according to guidelines.
To get started test the code above in Visual Studio, just create a new Console Application solution, type: install-package EntityFramework in the Package Manager Console and add an edmx file pointing to a local Northwind database. The main method will then just call the method above like this:
class Program
{
static void Main(string[] args)
{
Stopwatch sw = Stopwatch.StartNew();
var task = CustomHelper.SelectAllAsync();
task.Wait();
Console.WriteLine("Got data!");
List<Customer> data = task.Result;
Console.WriteLine(data.Count);
Console.WriteLine("Async op took: " + sw.ElapsedMilliseconds);
sw.Stop();
sw.Start();
//data =
//var data = CustomHelper.SelectAll();
//Console.WriteLine("Got data!");
//Console.WriteLine(data.Count);
//Console.WriteLine("Sync operation took: " + sw.ElapsedMilliseconds);
Console.WriteLine("Press any key to continue ...");
Console.ReadKey();
}
}
I see that the async operation takes a bit longer than the sync operation, so the async db call will have some time penalty but allows asynchronous processing, not freezing the calling code awaiting the result in a blocking fashion.

Calling stored procedure from Entity Framework 3.5

I"m using VS 2010 & EF 3.5. I've imported a stored procedure which returns a list of guids using the Function Import feature. How do I invoke it in my code? After instantiating the dbcontext, intellisense doesn't display the procedure I've imported. I know it's pretty easy in EF 4.0 but I'm stuck with EF 3.5 for this project. Any ideas on how get around this other than doing it the old-fashioned way?
I don't think EF versions prior to 4 can use imported stored procedures that don't return entities. That is, your stored procedure must return a complete entity object in order for EF to use it. Since your procedure only returns a list of GUIDs, EF doesn't know how to use it.
You can put this in your partial data-context class to call the procedure:
public IEnumerable<Guid> GetMyGUIDs()
{
if (this.Connection.State != System.Data.ConnectionState.Open)
this.Connection.Open();
var command = new System.Data.EntityClient.EntityCommand
{
CommandType = System.Data.CommandType.StoredProcedure,
CommandText = #"YourContext.YourProcedureName",
Connection = (System.Data.EntityClient.EntityConnection)this.Connection
};
var list = new List<Guid>();
using (var reader = command.ExecuteReader())
{
// get GUID values from the reader here,
// and put them in the list
reader.Close();
}
return list;
}

Add index with entity framework code first (CTP5)

Is there a way to get EF CTP5 to create an index when it creates a schema?
Update: See here for how EF 6.1 handles this (as pointed out by juFo below).
You can take advantage of the new CTP5’s ExecuteSqlCommand method on Database class which allows raw SQL commands to be executed against the database.
The best place to invoke SqlCommand method for this purpose is inside a Seed method that has been overridden in a custom Initializer class. For example:
protected override void Seed(EntityMappingContext context)
{
context.Database.ExecuteSqlCommand("CREATE INDEX IX_NAME ON ...");
}
As some mentioned in the comments to Mortezas answer there is a CreateIndex/DropIndex method if you use migrations.
But if you are in "debug"/development mode and is changing the schema all the time and are recreating the database every time you can use the example mentioned in Morteza answer.
To make it a little easier, I have written a very simple extension method to make it strongly typed, as inspiration that I want to share with anyone who reads this question and maybe would like this approach aswell. Just change it to fit your needs and way of naming indexes.
You use it like this: context.Database.CreateUniqueIndex<User>(x => x.Name);
.
public static void CreateUniqueIndex<TModel>(this Database database, Expression<Func<TModel, object>> expression)
{
if (database == null)
throw new ArgumentNullException("database");
// Assumes singular table name matching the name of the Model type
var tableName = typeof(TModel).Name;
var columnName = GetLambdaExpressionName(expression.Body);
var indexName = string.Format("IX_{0}_{1}", tableName, columnName);
var createIndexSql = string.Format("CREATE UNIQUE INDEX {0} ON {1} ({2})", indexName, tableName, columnName);
database.ExecuteSqlCommand(createIndexSql);
}
public static string GetLambdaExpressionName(Expression expression)
{
MemberExpression memberExp = expression as MemberExpression;
if (memberExp == null)
{
// Check if it is an UnaryExpression and unwrap it
var unaryExp = expression as UnaryExpression;
if (unaryExp != null)
memberExp = unaryExp.Operand as MemberExpression;
}
if (memberExp == null)
throw new ArgumentException("Cannot get name from expression", "expression");
return memberExp.Member.Name;
}
Update: From version 6.1 and onwards there is an [Index] attribute available.
For more info, see http://msdn.microsoft.com/en-US/data/jj591583#Index
This feature should be available in the near-future via data annotations and the Fluent API. Microsoft have added it into their public backlog:
http://entityframework.codeplex.com/workitem/list/basic?keywords=DevDiv [Id=87553]
Until then, you'll need to use a seed method on a custom Initializer class to execute the SQL to create the unique index, and if you're using code-first migrations, create a new migration for adding the unique index, and use the CreateIndex and DropIndex methods in your Up and Down methods for the migration to create and drop the index.
Check my answer here Entity Framework Code First Fluent Api: Adding Indexes to columns this allows you to define multi column indexes by using attributes on properties.