Created
September 4, 2015 17:17
-
-
Save MrDustpan/ca51a33db5bbce85b18b to your computer and use it in GitHub Desktop.
Example usage of async command/query implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class FetchUserByEmailQuery : IQuery<User> | |
{ | |
private readonly string email; | |
public FetchUserByEmailQuery(string email) | |
{ | |
this.email = email; | |
} | |
public async Task<User> ExecuteAsync(IDbConnection db) | |
{ | |
return db.QueryAsync<User>("select * from [User] where [Email] = @email", new { email }).FirstOrDefault(); | |
} | |
} | |
public class CreateUserCommand : ICommand | |
{ | |
private readonly User user; | |
public CreateUserCommand(User user) | |
{ | |
this.user = user; | |
} | |
public async Task ExecuteAsync(IDbConnection db) | |
{ | |
await db.ExecuteAsync("insert into [User] ([Email]) values (@Email)", user); | |
} | |
} | |
public class UserController | |
{ | |
private readonly IDatabase db; | |
public UserController(IDatabase db) | |
{ | |
this.db = db; | |
} | |
public async Task Create(string email) | |
{ | |
// See if the user exists | |
var user = await db.ExecuteAsync(new FetchUserByEmailQuery(email)); | |
if (user == null) | |
{ | |
// If not, create it | |
user = new User { Email = email }; | |
await db.ExecuteAsnyc(new CreateUserCommand(user)); | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment