在復雜業務邏輯中,使用C# CodeFirst可以幫助我們更好地組織和管理數據模型。以下是一些建議和最佳實踐:
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
}
public class MyDbContext : DbContext
{
public MyDbContext() : base("name=YourConnectionString")
{
}
public DbSet<User> Users { get; set; }
}
// 啟用遷移
Enable-Migrations
// 添加遷移
Add-Migration AddUserTable
// 更新數據庫
Update-Database
public interface IUserRepository
{
User GetUserById(int id);
void AddUser(User user);
// ...
}
public class UserRepository : IUserRepository
{
private readonly MyDbContext _context;
public UserRepository(MyDbContext context)
{
_context = context;
}
public User GetUserById(int id)
{
return _context.Users.Find(id);
}
public void AddUser(User user)
{
_context.Users.Add(user);
_context.SaveChanges();
}
// ...
}
public class UserService
{
private readonly IUserRepository _userRepository;
public UserService(IUserRepository userRepository)
{
_userRepository = userRepository;
}
public void RegisterUser(string name, string email)
{
var user = new User { Name = name, Email = email };
_userRepository.AddUser(user);
}
// ...
}
[TestFixture]
public class UserServiceTests
{
[Test]
public void RegisterUser_ValidInput_AddsUserToRepository()
{
var mockRepository = new Mock<IUserRepository>();
var service = new UserService(mockRepository.Object);
service.RegisterUser("John Doe", "john.doe@example.com");
mockRepository.Verify(x => x.AddUser(It.IsAny<User>()), Times.Once);
}
// ...
}
通過遵循這些建議和最佳實踐,您可以在復雜業務邏輯中更好地應用C# CodeFirst。這將有助于提高代碼的可讀性、可維護性和可測試性。