EntityFrameworkCore Demo in a WebAPI project.
Dependencies: .NET Core 2.2, Microsoft.EntityFrameworkCore v2.2
-
Apply EF Migration to your local SQL Server database
# if using Package Manger Console in Visual Studio Update-Database # if using console dotnet ef database update
-
Run Web App
In
WebBlogs.Web
folder, issue commanddotnet watch run
, then in browser navigate to http://localhost:5000/swagger/index.html. In Swagger page, you can try out APIs.Or, in Visual Studio, click run "IIS Express".
return await _dbContext.Authors
.Where(x => x.AuthorMembership == AuthorMembership.Gold ||
x.AuthorMembership == AuthorMembership.Platinum)
.Select(x => new AuthorViewModel(x))
.ToListAsync();
Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (44ms) [Parameters=[], CommandType='Text', ommandTimeout='30']
SELECT [x].[Id], [x].[AuthorMembership], [x].[FirstName], [x].LastName]
FROM [Authors] AS [x]
WHERE ([x].[AuthorMembership] = 2) OR ([x].[AuthorMembership] = 3)
public class Author
{
...
public static Expression<Func<Author, bool>> GoldAndUp = x =>
x.AuthorMembership == AuthorMembership.Gold ||
x.AuthorMembership == AuthorMembership.Platinum;
...
}
return await _dbContext.Authors
.Where(Author.GoldAndUp)
.Select(x => new AuthorViewModel(x))
.ToListAsync();
Microsoft.EntityFrameworkCore.Database.Command[20101]
Executed DbCommand (4ms) [Parameters=[], CommandType='Text', ommandTimeout='30']
SELECT [x].[Id], [x].[AuthorMembership], [x].[FirstName], [x].LastName]
FROM [Authors] AS [x]
WHERE ([x].[AuthorMembership] = 2) OR ([x].[AuthorMembership] = 3)
await _dbContext.Authors.Select(x => new AuthorViewModel(x)).ToListAsync();
Executed DbCommand (4ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT [x].[Id], [x].[AuthorMembership], [x].[FirstName], [x].[LastName]
FROM [Authors] AS [x]
public static Expression<Func<Author, AuthorViewModel>> Projection1
=> x => new AuthorViewModel
{
Id = x.Id,
FirstName = x.FirstName,
LastName = x.LastName
};
await _dbContext.Authors.Select(AuthorViewModel.Projection1).ToListAsync();
Executed DbCommand (1ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT [x].[Id], [x].[FirstName], [x].[LastName]
FROM [Authors] AS [x]
public static Expression<Func<Author, AuthorViewModel>> Projection2
=> x => new AuthorViewModel(x);
return await _dbContext.Authors.Select(AuthorViewModel.Projection2).ToListAsync();
Executed DbCommand (4ms) [Parameters=[], CommandType='Text', CommandTimeout='30']
SELECT [x].[Id], [x].[AuthorMembership], [x].[FirstName], [x].[LastName]
FROM [Authors] AS [x]
var authors = await _dbContext.Authors.ToListAsync();
return authors.Select(AuthorViewModel.Projection1.Compile()).ToList();