using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.ComponentModel.DataAnnotations;
public class User
{
public int Id {
get;
set; }
[
Required]
[
EmailAddress]
[
MaxLength(255)]
public string Email {
get;
set; } =
string.Empty;
[
Required]
[
MaxLength(100)]
public string Name {
get;
set; } =
string.Empty;
public UserRole Role {
get;
set; } =
UserRole.User;
public DateTime CreatedAt {
get;
set; } =
DateTime.UtcNow;
public DateTime UpdatedAt {
get;
set; } =
DateTime.UtcNow;
}
public enum UserRole
{
User,
Admin,
Moderator
}
public interface IUserRepository
{
Task<
User?> GetByIdAsync(
int id);
Task<
User?> GetByEmailAsync(
string email);
Task<
IEnumerable<
User>> GetAllAsync(
int page = 1,
int pageSize = 10);
Task<
User> CreateAsync(
User user);
Task<
User> UpdateAsync(
User user);
Task<
bool> DeleteAsync(
int id);
}
public class UserRepository :
IUserRepository
{
private readonly ApplicationDbContext _context;
public UserRepository(
ApplicationDbContext context)
{
_context = context;
}
public async Task<
User?> GetByIdAsync(
int id)
{
return await _context.Users
.AsNoTracking()
.FirstOrDefaultAsync(u => u.Id == id);
}
public async Task<
User?> GetByEmailAsync(
string email)
{
return await _context.Users
.AsNoTracking()
.FirstOrDefaultAsync(u => u.Email.ToLower() == email.ToLower());
}
public async Task<
IEnumerable<
User>> GetAllAsync(
int page = 1,
int pageSize = 10)
{
return await _context.Users
.AsNoTracking()
.OrderBy(u => u.Name)
.Skip((page - 1) * pageSize)
.Take(pageSize)
.ToListAsync();
}
public async Task<
User> CreateAsync(
User user)
{
_context.Users.Add(user);
await _context.SaveChangesAsync();
return user;
}
public async Task<
User> UpdateAsync(
User user)
{
user.UpdatedAt =
DateTime.UtcNow;
_context.Users.Update(user);
await _context.SaveChangesAsync();
return user;
}
public async Task<
bool> DeleteAsync(
int id)
{
var user =
await _context.Users.FindAsync(id);
if (user ==
null)
return false;
_context.Users.Remove(user);
await _context.SaveChangesAsync();
return true;
}
}
public interface IUserService
{
Task<
UserDto?> GetUserByIdAsync(
int id);
Task<
IEnumerable<
UserDto>> GetAllUsersAsync(
int page,
int pageSize);
Task<
UserDto> CreateUserAsync(
CreateUserRequest request);
Task<
UserDto?> UpdateUserAsync(
int id,
UpdateUserRequest request);
Task<
bool> DeleteUserAsync(
int id);
}
public class UserService :
IUserService
{
private readonly IUserRepository _userRepository;
private readonly IMapper _mapper;
private readonly ILogger<
UserService> _logger;
public UserService(
IUserRepository userRepository,
IMapper mapper,
ILogger<
UserService> logger)
{
_userRepository = userRepository;
_mapper = mapper;
_logger = logger;
}
public async Task<
UserDto?> GetUserByIdAsync(
int id)
{
var user =
await _userRepository.GetByIdAsync(id);
return user !=
null ? _mapper.Map<
UserDto>(user) :
null;
}
public async Task<
UserDto> CreateUserAsync(
CreateUserRequest request)
{
var existingUser =
await _userRepository.GetByEmailAsync(request.Email);
if (existingUser !=
null)
{
throw new InvalidOperationException(
$"User with email {request.Email} already exists");
}
var user = _mapper.Map<
User>(request);
var createdUser =
await _userRepository.CreateAsync(user);
_logger.LogInformation(
"User created with ID: {UserId}", createdUser.Id);
return _mapper.Map<
UserDto>(createdUser);
}
}
[
ApiController]
[
Route(
"api/[controller]")]
public class UsersController :
ControllerBase
{
private readonly IUserService _userService;
public UsersController(
IUserService userService)
{
_userService = userService;
}
[
HttpGet(
"{id}")]
World C# Benefits
Enterprise Development
- Rapid API development: ASP.NET Core scaffolding and configuration
- Database integration: Entity Framework migrations and optimization
- Cloud-native patterns: Azure integration and microservices architecture
- Security best practices: Authentication, authorization, and data protection
Developer Productivity
- Type safety: Compile-time error detection and IntelliSense
- Rich ecosystem: NuGet packages and .NET libraries
- Cross-platform: Windows, Linux, and macOS deployment
- Performance: JIT compilation and runtime optimizations
Get Started with C# AI Coding
Transform your .NET development with AI agents that understand the Microsoft ecosystem, from ASP.NET Core to Azure cloud services. Our autonomous programming system accelerates enterprise development while ensuring scalability and maintainability.
Ready to experience enterprise .NET AI development? Start with a free trial and see how our specialized C# agents can revolutionize your Microsoft technology stack development.
← Back to Languages
← Back to syntax.ai