2015-06-16 95 views
0

我使用Web API創建了REST服務,我使用EF Code First。 我的問題是,當我添加一個現有關係foreignId = 1的實體時,EF給我添加了關係並將我的實體返回給foreignId = 2EF 6和Web API使用現有實體添加實體

POST object 
{ 
"nom":"Test", 
"actif":true, 
"provinceId":1, 
"province":{ 
    "id": 1, 
    "nom": "Province ok", 
    "actif": true 
} 
} 

Return object 

    { 
     "id": 1, 
     "nom": "Test", 
     "actif": true, 
     "provinceId": 2, 
     "province": { 
      "id": 2, 
      "nom": "Province ok" 
     }, 

    } 

我也會使用這種風格的存儲庫模式。

 public abstract class ServiceCrud<TEntity> : ServiceBase 
      where TEntity : EntityBase 
     { 

      public virtual object Get() 
      { 
       // Context. 
       return Ctx.Set<TEntity>().OrderBy(x => x.Nom).ToList(); 

      } 

      public virtual async Task<object> Get(int id) 
      { 
       // Context. 
       var entity = await Ctx.Set<TEntity>().FindAsync(id); 

       // Return. 
       return entity; 
      } 

      public virtual async Task<object> Add(TEntity entity) 
      { 
       // Check Validity. 
       CheckValidity(entity); 

       // Context. 
       Ctx.Set<TEntity>().Add(entity); 
       await Ctx.SaveChangesAsync(); 

       // Return. 
       return entity; 
      } 

      public virtual async Task<object> Update(TEntity entity) 
      { 
       // Check Validity. 
       CheckValidity(entity); 

       // Context. 
       Ctx.Entry(entity).State = EntityState.Modified; 
       await Ctx.SaveChangesAsync(); 

       // Return. 
       return entity; 
      } 

      public virtual void CheckValidity(TEntity entity) 
      { 
       // Nom unique. 
       var entityBase = Ctx.Set<TEntity>().AsNoTracking().FirstOrDefault(x => x.Nom == entity.Nom); 

       if (entityBase != null && (entity.Id == null || entity.Id != entityBase.Id)) 
        throw new ValidationException("Le nom doit être unique"); 

      } 
     } 

謝謝你的幫忙。

Alex

回答

0

如果我重寫我的方法,那沒關係。

public override async Task<object> Add(Commune entity) 
    { 
     // Check Validity. 
     CheckValidity(entity); 

     // Context. 
     Ctx.Set<Commune>().Add(entity); 
     Ctx.Set<Province>().Attach(entity.Province); 

     await Ctx.SaveChangesAsync(); 

     // Return. 
     return entity; 
    } 

但是有沒有更通用的方法?