0

我正在尝试做看起来相当简单的事情,但我得到了一个空引用....

我在最后一个语句中的 assoc files 属性上有一个 null ......

TestInfo.AggregateRoutes.MainBlogEntry = new Blog { BlogType = 1, Title = TestInfo.UniqueRecordIdentifier, Description = TestInfo.UniqueRecordIdentifier, DateAdded = DateTime.Now, User = TestInfo.UniqueRecordIdentifier };


IBlogRepository blogRepo = new BlogRepository();
var assocFile = new AssocFile { Name = TestInfo.UniqueRecordIdentifier, Url = TestInfo.UniqueRecordIdentifier };

TestInfo.AggregateRoutes.MainBlogEntry.AssocFiles.Add(assocFile);

这是我为支持我正在尝试做的事情而编写的代码......

public class PteDotNetContext : DbContext
    {
        public DbSet<Blog> Blogs { get; set; }
        public DbSet<AssocFile> AssocFiles { get; set; }
    }

 public class Blog
    {

        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int BlogId { get; set; }
        public int BlogType { get; set; }
        public string Title { get; set; }
        public string Description { get; set; }
        public DateTime DateAdded { get; set; }
        public string User { get; set; }

        public virtual ICollection<AssocFile> AssocFiles { get; set; }
    }

 public class AssocFile
    {

        [Key]
        [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
        public int AssocFileId { get; set; }

        public int BlogId { get; set; }
        public string Url { get; set; }
        public string Name { get; set; }

        public virtual Category Category { get; set; }
    }

我认为声明它是虚拟的重点是它会创建一个外键约束?

4

1 回答 1

0

当您实例化一个实体时,您还需要在第一次访问它之前初始化集合导航属性。在你的情况下MainBlogEntry.AssocFiles = new List<AssocFile>();。原因是,您的属性实现不包含任何初始化集合的逻辑。

当 EF 创建您的实体的新实例时,它会将您的实体子类化(即代理创建)并覆盖您的属性的默认功能。

TestInfo.AggregateRoutes.MainBlogEntry = new Blog { BlogType = 1, Title = TestInfo.UniqueRecordIdentifier, Description = TestInfo.UniqueRecordIdentifier, DateAdded = DateTime.Now, User = TestInfo.UniqueRecordIdentifier };


IBlogRepository blogRepo = new BlogRepository();
var assocFile = new AssocFile { Name = TestInfo.UniqueRecordIdentifier, Url = TestInfo.UniqueRecordIdentifier };

TestInfo.AggregateRoutes.MainBlogEntry.AssocFiles = new List<AssocFile>();

TestInfo.AggregateRoutes.MainBlogEntry.AssocFiles.Add(assocFile);
于 2012-04-13T13:33:30.877 回答