I get a NullReferenceException when my target provider is SQL Server CE, but with SQL Server Express it works. I get the exception on the return... when I’m trying to access the Comments. Model is very simple and it can be inferred from the code. Thanks for any help! I’m using Entity Framework code-first 4.3 and SQL Server CE 4.0 by the way.
-
using the same code with SQL Server Express as provider = runs fine
-
using the same code with SQL Server CE as provider = exception error
In addition, I have no problems with SQL Server CE. It works on my machine and I have done single-table operations with Entity Framework code-first and even asp.net authorization. I have never done any nested addition/deletion like this on related entities though so I’m curious as to why this doesn’t work..
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;
What stumps me also is that in SQL Server Express, if I examine the data, the comments are there.
In SQL Server CE, only the Persons table has data while the Comments table is empty.
EDIT:
If it helps, here is the model:
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; }
}
The problem is that: SQL CE error details are a lot more vague than when using SQL Server Express as provider therefore the confusion and the vague direction.
SQLCE Exception details is something like:
NullException
SQLExpress Exception details is something like:
The model backing the ‘MyContext’ context has changed since the database was created. Consider using Code First Migrations to update the database (http://go.microsoft.com/fwlink/?LinkId=238269).
The solution is: to sync the models by adding this code:
Database.SetInitializer(new DropCreateDatabaseAlways<MyContext>());