:
Bir süre önce MS' forumlarda tam soru soruldu. İkincisi, bileşik anahtarlara sahip varlıklar içindir. İlkinden daha fazla çirkin, ama işe yarıyor.
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;
}
}
Örnek kullanım: Ben DBContext kullanıyorum
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; });
Bu hala doğru değil, değil mi? – R0MANARMY
Evet, öyle. Ve bu üzücü. –