2009-05-12 13 views
0

ApplyPropertyChangesのときに例外が発生するのはなぜですか?ヘルプLinq to Sql

私のユーザーテーブルを編集しているのに、私のニューステーブルで作業していないときのコードはほぼ同じです。

、作成、削除、および詳細は、すべて正常に動作しているが、私は以下の例外を取得していますニュースを編集しようとすると:

ObjectStateManagerがObjectStateEntry「MagixCMS.Models.noticia」が含まれていません

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 

namespace MagixCMS.Models 
{ 
    public class NoticiaRepository : INoticiaRepository 
    { 
     #region INoticiaRepository Members 

     magixcmsEntities _entities = new magixcmsEntities(); 

     public noticia CreateNoticia(noticia noticiaToCreate) 
     { 
      _entities.AddTonoticiaSet(noticiaToCreate); 
      _entities.SaveChanges(); 
      return noticiaToCreate; 
     } 

     public void DeletaNoticia(noticia noticiaToDelete) 
     { 
      var noticiaOriginal = GetNoticia(noticiaToDelete.Id); 
      _entities.DeleteObject(noticiaOriginal); 
      _entities.SaveChanges(); 
     } 

     public noticia EditNoticia(noticia noticiaToEdit) 
     { 
      var noticiaOriginal = GetNoticia(noticiaToEdit.Id); 
      _entities.ApplyPropertyChanges(noticiaToEdit.EntityKey.EntitySetName, noticiaToEdit); //EXCEPTION HERE 
      _entities.SaveChanges(); 
      return noticiaToEdit; 
     } 

     public noticia GetNoticia(int id) 
     { 
      return (from c in _entities.noticiaSet where c.Id == id select c).FirstOrDefault(); 
     } 

     public IEnumerable<noticia> ListNoticias() 
     { 
      return _entities.noticiaSet.ToList(); 
     } 

     #endregion 
    } 
} 

Googleの例外はありますが、多くのヘルプが見つかりませんでした。

+0

は、あなたが元をフェッチしているいずれかの理由がありますEditNoticiaメソッドでオブジェクトを戻します - 使用されていないようですか? – RobS

答えて

0

私はそれを解決します。

問題はEFモデル上です。

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Data.Objects; 
using System.Data.Objects.DataClasses; 

namespace MagixCMS.Models 
{ 
    public static class Extensions 
    { 
     public static void Update(ObjectContext context, string entitySetName, IEntityWithKey entity) 
     { 
      entity.EntityKey = context.CreateEntityKey(entitySetName, entity); 
      context.Attach(entity); 
      var stateEntry = context.ObjectStateManager.GetObjectStateEntry(entity.EntityKey); 
      var propertyNameList = stateEntry.CurrentValues.DataRecordInfo.FieldMetadata.Select(pn => pn.FieldType.Name); 
      foreach (var propName in propertyNameList) 
      { 
       stateEntry.SetModifiedProperty(propName); 
      } 
     } 
    } 
} 

そして、あなたがEditメソッドに:あなたはあなたのデータを永続化するために拡張メソッドが必要になりますそれを解決するために

public noticia EditNoticia(noticia noticiaToEdit) 
{ 
    //GET THE CONTEXT FOR THE ENTITY 
    ObjectContext _context = this._entities.noticiaSet.Context; 
    var noticiaOriginal = GetNoticia(noticiaToEdit.Id); 
    //UPDATE THE ORIGINAL ENTITY WITH THE NEW VALUES 
    Extensions.Update(_context, noticiaOriginal.EntityKey.EntitySetName, noticiaToEdit); 
    //PERSIST THE DATA 
    _entities.SaveChanges(); 
    return noticiaToEdit; 
}