2011-07-15 5 views

Trả lời

0

Không có tương đương tại thời điểm này.

Bạn có thể thử điều này tuy nhiên, giả sử bạn sẽ không thực hiện bất kỳ thay đổi nào đối với danh mục.

Entity Framework 4.0:

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

Entity Framework 4.1:

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

MSDN link

+0

Tôi đang sử dụng DbContext, không ObjectContext – Hao

+0

Chỉ có một thay đổi nhỏ với EF4.1: context.Categories.Attach (mèo); – BennyM

2

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