2011-07-15 6 views

答えて

9

は同等ではありませんし、おそらくどのようにEFの基本的な設計上の欠陥の存在になることはありませんレイジーローディングを行います。

私はMS」フォーラムでしばらく前にあなたの正確な質問を:ここでhttp://social.msdn.microsoft.com/Forums/en-US/adonetefx/thread/fccfcf68-2b53-407f-9a87-a32426db6f36

+0

これはまだ当てはまりませんか? – R0MANARMY

+1

はい、そうです。それは悲しいことです。 –

0

現時点では同等ではありません。

ただし、カテゴリに変更を加えないと仮定すると、これを試すことができます。

エンティティフレームワーク4.0:

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

エンティティフレームワーク4.1:

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

MSDN link

+0

、EF4.1ではないのObjectContext – Hao

+0

つだけ小さな変更: context.Categories.Attach(猫)。 – BennyM

2

は、私はNHibernateはの負荷をエミュレートするために作成したいくつかの拡張メソッドです。 2つ目は複合キーを持つエンティティです。最初のものよりずっと醜いですが、うまくいきます。

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

使用例:私はDbContextを使用してい

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; }); 
関連する問題