为什么此代码适用于SQL Server Express但*不适用于* SQL Server CE?

时间:2012-04-05 20:05:04

标签: c# sql-server entity-framework sql-server-ce nullreferenceexception

当我的目标提供程序是SQL Server CE时,我得到NullReferenceException,但是使用SQL Server Express它可以正常工作。当我尝试访问return...时,我在Comments上获得了例外。模型非常简单,可以从代码中推断出来。谢谢你的帮助!我顺便使用Entity Framework代码优先4.3和SQL Server CE 4.0。

  • 使用与SQL Server Express相同的代码作为provider =运行正常

  • 使用与SQL Server CE相同的代码作为provider = exception error

此外,我对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; }
}

1 个答案:

答案 0 :(得分:1)

问题在于: SQL CE错误细节比使用SQL Server Express作为提供程序时更加模糊因此存在混淆和模糊的方向。

SQLCE异常详情如下:

NullException

SQLExpress异常详情如下:

自创建数据库以来,支持“MyContext”上下文的模型已更改。请考虑使用“代码优先迁移”来更新数据库(http://go.microsoft.com/fwlink/?LinkId=238269)。

解决方案是:通过添加以下代码来同步

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

相关问题