您好,登錄后才能下訂單哦!
在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();
// 根據(jù)ID獲取用戶
var userById = userRepository.GetById(1);
// 更新用戶
userById.Age = 31;
userRepository.Update(userById);
// 刪除用戶
userRepository.Delete(1);
}
}
這樣,你就使用C#和Entity Framework Core模擬了Spring的Spring Data JPA的Repository模式。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。