0

當我的目標提供者是SQL Server CE時,我得到了一個NullReferenceException,但是它與SQL Server Express一起工作。當我嘗試訪問Comments時,我在return...上遇到了異常情況。模型非常簡單,可以從代碼中推斷出來。謝謝你的幫助!順便說一句,我使用Entity Framework代碼優先4.3和SQL Server CE 4.0。爲什麼此代碼適用於SQL Server Express,但不* SQL Server CE?

  • 使用與SQL Server Express相同的代碼提供商=運行正常

  • 使用與SQL Server CE作爲供應商=異常錯誤

除了相同的代碼,我有SQL Server CE沒有問題。它在我的機器上工作,我已經用Entity Framework代碼優先和甚至asp.net授權完成單表操作。我從來沒有做過任何像這樣的嵌套添加/刪除有關的實體,但這樣我很好奇,爲什麼這不工作..

  db.Persons.Add(new Person() 
      { 
       FullName = "JC Viray", 
       Comments = new List<Comment>(){ 
         new Comment(){CommentContent="Hello!"}, 
         new Comment(){CommentContent="World!"} 
      } 
      }); 

      db.SaveChanges(); 

      return db.Persons.FirstOrDefault().Comments.FirstOrDefault().CommentContent; 

什麼樹樁我也就是在SQL Server Express,如果我檢查數據,評論在那裏。

在SQL Server CE中,只有Persons表具有數據,而Comments表爲空。

編輯:

如果有幫助,這裏是模型:

public class Person 
{ 
    [Key] 
    public int PersonId { get; set; } 
    public string FullName { get; set; } 

    public virtual ICollection<Comment> Comments { get; set; } 
} 

public class Comment 
{ 
    [Key] 
    public int CommentId { get; set; } 
    public string CommentContent { get; set; } 

    [ForeignKey("Person")] 
    public int PersonId { get; set; } 
    public virtual Person Person { get; set; } 
} 
+0

什麼是您使用的SQL Server Compact版本? – AFD 2012-04-05 20:12:40

+0

如果您使用斷點進行調試,您是否可以看到人員是否包含任何內容?原因Persons.FirstOrDefault()可以返回NULL,如果找不到可能導致NullReference的任何內容。 Samething with Comments.FirstOrDefault()。如果沒有手中的代碼,很難看到,但可以在調試時檢查它。祝你好運。 – 2012-04-05 20:13:53

+0

我把它安裝在我的項目上,從我的機器上,我從官方頁面安裝它,所以最新的.. 4.0.8852。1 – 2012-04-05 20:14:06

回答

1

的問題是:SQL CE錯誤的細節有很多使用SQL Server Express作爲供應商時相比,較爲模糊因此混亂和模糊的方向。

SQLCE異常詳細信息是一樣的東西:

NullException

的SQLExpress異常詳細信息是這樣的:

模型靠山 'MyContext' 語境已經改變該數據庫已創建。考慮使用Code First Migrations來更新數據庫(http://go.microsoft.com/fwlink/?LinkId=238269)。

的解決方案是:通過將此代碼添加到同步型號:

Database.SetInitializer(new DropCreateDatabaseAlways<MyContext>());

+0

有關初始化SQL Server 4.0 compact的方式,請查看http://www.microsoft.com/download/en/details.aspx?displaylang=en&id=27290。你也可以考慮數據庫遷移,如果你的模型不斷變化http://blogs.msdn.com/b/adonet/archive/2012/02/09/ef-4-3-automatic-migrations-walkthrough.aspx – AFD 2012-04-06 21:38:20

+0

@AndreiDrynov謝謝你的信息!絕對是一個偉大的幫助:) – 2012-04-07 05:00:43

相關問題