I have created a small database on a SQL Server on a remote computer with a couple of tables, called Document
, File
and Tag
. The relations are quite simple: File->Document: one-to-many, Tag->Document: many-to-many. So I created a link table called document_tag where I store the document and tag Id's.
I then asked Entity Framework to create the corresponding code for me, which resulted in a couple of classes. Everything worked perfectly, except the performance was a bit slow, so I decided to create a .SDF
file (SQL Server CE database), keep the code that talks to the models and let Entity Framework re-create the models.
After this, when I simply run the following code
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();
Everything works fine and the document, file and tag is stored.
However, when I just add the line to assign the tag to the document:
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();
I get the exception
Value cannot be null. Parameter name: source
on the SaveChanges()
call. Does anyone know what I'm doing wrong here?
Ok. It turns out I needed to specify both the document and tag id in the documents_tag table as Primary Key. The error sent me the wrong way but when I tried to re-create the scenario in an empty solution I got this error when generating the code from the database:
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.
That was the clue to this solution. Hope it helps anyone else. You need to re-create the models after modifying the database. Maybe refreshing is enough, I re-created everything.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.