在C#中,我们可以使用Entity Framework Core来模拟Spring的Spring Data JPA的Repository模式
public class User
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}
DbContext
的类(DbContext):using Microsoft.EntityFrameworkCore;
public class ApplicationDbContext : DbContext
{
public DbSet<User> Users { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer("YourConnectionStringHere");
}
}
RepositoryBase<TEntity>
的类(RepositoryBase):using System.Linq;
public class RepositoryBase<TEntity> : DbContext
{
protected readonly ApplicationDbContext _context;
protected readonly DbSet<TEntity> _dbSet;
public RepositoryBase(ApplicationDbContext context)
{
_context = context;
_dbSet = context.Set<TEntity>();
}
public IQueryable<TEntity> GetAll()
{
return _dbSet;
}
public TEntity GetById(int id)
{
return _dbSet.Find(id);
}
public void Insert(TEntity entity)
{
_dbSet.Add(entity);
_context.SaveChanges();
}
public void Update(TEntity entity)
{
_dbSet.Attach(entity);
_context.Entry(entity).State = EntityState.Modified;
_context.SaveChanges();
}
public void Delete(int id)
{
var entity = _dbSet.Find(id);
if (entity != null)
{
_dbSet.Remove(entity);
_context.SaveChanges();
}
}
}
RepositoryBase<User>
的类(UserRepository):public class UserRepository : RepositoryBase<User>
{
public UserRepository(ApplicationDbContext context) : base(context) { }
}
UserRepository
:public class Program
{
public static void Main(string[] args)
{
using var context = new ApplicationDbContext();
var userRepository = new UserRepository(context);
// 添加一个新用户
var newUser = new User { Name = "John Doe", Age = 30 };
userRepository.Insert(newUser);
// 获取所有用户
var allUsers = userRepository.GetAll();
// 根据ID获取用户
var userById = userRepository.GetById(1);
// 更新用户
userById.Age = 31;
userRepository.Update(userById);
// 删除用户
userRepository.Delete(1);
}
}
这样,你就使用C#和Entity Framework Core模拟了Spring的Spring Data JPA的Repository模式。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。