简体   繁体   中英

Entity Framework 6 Async DBContext Access with Enums

I'm utilizing EF 6's ability to utilize Enum's as properties in an entity object.

When I try querying the datasource asynchronously using this enum property as part of the criteria, the query never returns. However, if I make the query synchronously it completes successfully. The SQL generated by EF is identical for both cases, and is correct.

Here a simplified version of my entity object :

public class RoleGroup {
    public int Id { get; set; }

    [Column("RequestSubTypeId")]
    public SubTypeEnum? SubTypeId { get; set; }
}

Here's a simplified version of my enum :

public enum SubTypeEnum {
    AccountsPayableInquiry = 1,
    PayrollInquiry = 2,
    BillingInquiry = 3
}

Here's the method I'm using to retrieve a role group from the database, based on the subTypeId parameter:

public async Task<RoleGroup> GetRoleGroupBySubType(SubTypeEnum subTypeId) {
    return await Context.WorkflowRoleGroups
                        .FirstAsync(roleGroup => roleGroup.SubTypeId == subTypeId);
}

Using Context.Database.Log = s => Debug.WriteLine(s); I'm able to see that the following SQL is produced by the above method:

SELECT TOP (1) 
    [Extent1].[Id] AS [Id], 
    [Extent1].[RequestSubTypeId] AS [RequestSubTypeId]
FROM  [dbo].[WorkflowRoleGroups] AS [Extent1]
WHERE [Extent1].[RequestSubTypeId] = @p__linq__0

-- p__linq__0: '1' (Type = Int32, IsNullable = false)

However, that's as far as execution gets. Nothing happens, no errors are thrown. In the output window I see "The Thread has exited with code 0".

When I make the method synchronous, like the below example, the correct results are returned from the database and all is well. The SQL query generated is identical to the async one.

public RoleGroup GetRoleGroupBySubType(SubTypeEnum subTypeId) {
    return Context.WorkflowRoleGroups
                  .First(roleGroup => roleGroup.SubTypeId == subTypeId);
}

I'd appreciate any guidance in understanding why using async in with an enum as part of the criteria causes this issue.

It probably has nothing to do with EF but something to do with your use of async/await and mixing it with something like Task.Result (which will cause a deadlock) in the call stack. The entire call stack should use the async/await at every point (also called async all the way). Without seeing all the other code in the call stack there is no way to know what part is causing the deadlock.

Here is a good source for understanding why/how the deadlock can occur Don't Block on Async Code . Stephen Cleary (author of the referenced article) also commonly responds to async-await questions on SO.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM