簡體   English   中英

帶有SQL Server CE數據庫的實體框架:多對多關系給出了例外,“值不能為null。 參數名稱:來源”

[英]Entity Framework with SQL Server CE database: many-to-many relation gives exception “Value cannot be null. Parameter name: source”

我在遠程計算機上的SQL Server上創建了一個小型數據庫,其中包含幾個表,分別稱為DocumentFileTag 關系非常簡單:文件->文檔:一對多,標簽->文檔:多對多。 因此,我創建了一個名為document_tag的鏈接表,用於存儲文檔和標簽ID。

然后,我要求Entity Framework為我創建相應的代碼,這產生了兩個類。 一切工作正常,除了性能稍慢,所以我決定創建一個.SDF文件(SQL Server CE數據庫),保留與模型對話的代碼,然后讓Entity Framework重新創建模型。

之后,當我簡單地運行以下代碼時

var doc = new Document { Name = "Test", Documentdate = new DateTime( 2010, 1, 2 };
var file = new File{ Document = doc, Filename = "test.txt", Scandate = new DateTime( 2010, 1, 3 ) };
var tag1 = new Tag { Name = "test-tag" };

_db.documents.Add(doc);
_db.files.Add(file);
_db.tags.Add(tag1);

_db.SaveChanges();

一切正常,文檔,文件和標簽已存儲。

但是,當我僅添加行以將標簽分配給文檔時:

var doc = new Document { Name = "Test", Documentdate = new DateTime( 2010, 1, 2 };
var file = new File{ Document = doc, Filename = "test.txt", Scandate = new DateTime( 2010, 1, 3 ) };
var tag1 = new Tag { Name = "test-tag" };
_db.documents.Add(doc);
tag1.Documents.Add(doc);
_db.files.Add(file);
_db.tags.Add(tag1);
_db.SaveChanges();

我例外

值不能為空。 參數名稱:來源

SaveChanges()調用上。 有人知道我在做什么錯嗎?

好。 事實證明,我需要在documents_tag表中同時指定文檔和標簽ID作為主鍵。 該錯誤以錯誤的方式發送給我,但是當我嘗試在空解決方案中重新創建場景時,從數據庫生成代碼時出現此錯誤:

The table/view 'document_tag' does not have a primary key defined. The key has been inferred and the definition was created as a read-only table/view.

這就是解決方案的線索。 希望它對其他人有幫助。 修改數據庫后,您需要重新創建模型。 也許刷新就足夠了,我重新創建了所有內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM