Dưới đây là một số phương pháp mở rộng Tôi đã tạo để mô phỏng tải NHibernate. Thứ hai là dành cho các thực thể có các phím tổng hợp. Nhiều xấu hơn để sử dụng hơn cái đầu tiên, nhưng nó hoạt động.
public static class EntityFrameworkExtensions
{
public static TEntity LoadEntity<TEntity,TId>(this DbContext context, TId id) where TEntity : EntityBase<TId>, new()
{
var entity = context.ChangeTracker.Entries<TEntity>().SingleOrDefault(e => e.Entity.Id.Equals(id))?.Entity;
if (entity == null)
{
entity = new TEntity { Id = id };
context.Set<TEntity>().Attach(entity);
}
return entity;
}
public static TEntity LoadEntity<TEntity>(this DbContext context, Func<TEntity, bool> predicate, Action<TEntity> idAssignmentAction) where TEntity : class, new()
{
var entity = context.ChangeTracker.Entries<TEntity>().SingleOrDefault(e => predicate(e.Entity))?.Entity;
if (entity == null)
{
entity = new TEntity();
idAssignmentAction(entity);
context.Set<TEntity>().Attach(entity);
}
return entity;
}
}
Ví dụ sử dụng:
var account = _dbContext.LoadEntity<Account, int>(request.AccountId);
var composite = _dbContext.LoadEntity<AccountWithComposite>(a => a.X == 1 && a.Y == 2, a => { a.X = 1; a.Y = 2; });
Nguồn
2017-04-02 02:08:37
Điều đó vẫn không đúng, phải không? – R0MANARMY
Vâng, đúng thế. Và thật buồn. –