2011-07-15 19 views
8

Aşağıdaki NHibernate tembel yüklemesi Entity Framework'e eşdeğerdir? NHibernate session.Lity Framework'te eşdeğer mi?

product.Categories.Add(s.Load<Category>(cat)); 

Bunu denedim, ama veritabanından Kategori tablo okuyun:

product.Categories.Add(db.Categories.Find(cat)); 

cevap

0

anda eşdeğeri yoktur.

Ancak, kategoride herhangi bir değişiklik yapmayacağınızı varsayarak bunu deneyebilirsiniz.

Varlık Framework 4.0:

Category cat = new Category(); 
cat.Id = i; 
context.Attach("Categories", cat); 
product.Categories.Add(cat); 

Varlık Framework 4.1:

Category cat = new Category(); 
cat.Id = i; 
context.Categories.Attach(cat); 
product.Categories.Add(cat); 

MSDN link

+0

, EF4.1 ile değil ObjectContext – Hao

+0

Tek bir küçük değişiklik: context.Categories.Attach (kedi); – BennyM

2

:

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; });