2010-02-12 46 views
0

我有一些簡單的代碼的問題,我重構了一些現有的代碼從LINQ到SQL到實體框架。我測試我的保存和刪除,並刪除真的竊聽我:使用實體框架(C#)刪除異常

[TestMethod] 
public void TestSaveDelete() 
{ 
    ObjectFactory.Initialize(x => 
    { 
     x.For<IArticleCommentRepository>().Use<ArticleCommentRepository>(); 
    }); 

    PLArticleComment plac = new PLArticleComment(); 
    plac.Created = DateTime.Now; 
    plac.Email = "myemail"; 
    plac.Name = "myName"; 
    plac.Text = "myText"; 
    plac.Title = "myTitle"; 

    IArticleCommentRepository acrep = ObjectFactory.GetInstance<IArticleCommentRepository>(); 
    try 
    { 
     PortalLandEntities ple = new PortalLandEntities(); 
     int count = ple.PLArticleComment.Count(); 
     acrep.Save(plac); 
     Assert.AreEqual(ple.PLArticleComment.Count(), count + 1); 
     //PLArticleComment newPlac = ple.PLArticleComment.First(m => m.Id == plac.Id); 
     //ple.Attach(newPlac); 
     acrep.Delete(plac); 
     Assert.AreEqual(ple.PLArticleComment.Count(), count + 1); 
    } 
    catch (Exception ex) 
    { 
     Console.WriteLine(ex.Message); 
    } 
} 

每次我嘗試運行這段代碼,我得到的delete語句異常,告訴我,它不包含內當前ObjectStateManager.Please注意,這兩個我保存和刪除這個樣子的:

public void Delete(PLCore.Model.PLArticleComment comment) 
{ 
    using (PortalLandEntities ple = Connection.GetEntityConnection()) 
    { 
     ple.DeleteObject(comment); 
     ple.SaveChanges(); 
    } 
} 

public void Save(PLCore.Model.PLArticleComment comment) 
{ 
    using (PortalLandEntities ple = Connection.GetEntityConnection()) 
    { 
     ple.AddToPLArticleComment(comment); 
     ple.SaveChanges(); 
    } 
} 

和連接啄:

public class Connection 
{ 
    public static PortalLandEntities GetEntityConnection() 
    { 
     return new PortalLandEntities(); 
    } 
} 

什麼我可以做,使它瓦特任何想法掃?

+0

它是「實體框架」,而不是「實體模型框架」。另外,我建議擺脫使用ex.Message的習慣。改用ex.ToString()。 – 2010-02-12 19:45:08

回答

1

你不能從一個ObjectContext(在你的情況下,ObjectContextPortalLandEntities實例)加載一個實體,然後從另一個ObjectContext刪除它,除非你從第一次分離,並將其連接到第二位。如果您一次只使用一個ObjectContext,那麼您的生活將會非常簡單得多。如果你不能那樣做,你必須首先手動Detach然後,同時跟蹤哪些實體連接到哪個ObjectContext

如何使用DI與您的Connection:使其非靜態。

public class Connection 
{ 
    private PortalLandEntities _entities; 

    public PortalLandEntities GetEntityConnection() 
    { 
     return _entities; 
    } 

    public Connection(PortalLandEntities entities) 
    { 
     this._entities = entities; 
    } 
} 

然後每個請求使用DI容器。大多數人通過控制器工廠來做到這一點。

+0

我將如何實現我的「連接」類的新版本?我喜歡現在的結構,因爲我可以只改變一個地方的數據庫,並在必要時重載getConnection ...我應該做一個單身人士嗎? – 2010-02-12 19:25:12

+0

使用DI爲每個請求注入一個ObjectContext實例,而不是在內部新建一個。請注意,這也會讓你的課更具可測性。 – 2010-02-12 20:04:27

+0

好吧,想你失去了我。我將如何去做這個DI?你能否寫下方法簽名?那麼如何解決我的「保存」和「刪除」,他們是否應該將ObjectContect作爲參數? (我真的很討厭這個問題,想讓客戶端看不見它)。請注意,即時使用StructureMap作爲我的IOC。 – 2010-02-12 20:13:44