0
我有3個模型與映射。多對多映射/種子
問題是,當我嘗試種子他們我得到NullReferenceException。
[Table("Articles")]
public class Article
{
[Required]
public int Id { get; set; }
public string Title { get; set; }
public DateTime Date { get; set; }
public string Text { get; set; }
public virtual List<Comment> Comments { get; set; }
public virtual List<Tag> Tags { get; set; }
}
[Table("Tags")]
public class Tag
{
[Required]
public int Id { get; set; }
[Required]
public string Name { get; set; }
public virtual List<Article> Articles { get; set; }
}
[Table("Comments")]
public class Comment
{
[Required]
public int Id { get; set; }
[Required]
[DataType(DataType.MultilineText)]
public string Text { get; set; }
public DateTime Date { get; set; }
[Required]
public virtual Article Article { get; set; }
}
public ArticleMapping()
{
this.HasKey(m => m.Id);
this.HasMany(m => m.Comments);
this.HasMany(m => m.Tags);
}
public CommentMapping()
{
this.HasKey(m => m.Id);
this.HasRequired(m => m.Article);
}
public TagMapping()
{
this.HasKey(m => m.Id);
this.HasMany(m => m.Articles);
}
這也是我種子數據的方式:
protected override void Seed(MychineContext context)
{
Article article = new Article();
article.Title = "Looking for trouble";
article.Date = DateTime.Now;
article.Text = "Lorem ipsum dolor sit amet";
context.Articles.Add(article);
Tag tag = new Tag();
tag.Name = "PHP";
tag.Articles.Add(article);
article.Tags.Add(tag);
context.Articles.Attach(article);
context.SaveChanges();
base.Seed(context);
}
這是映射關係是否正確?如果我使用「遷移」,我將需要每次重置所有數據?
NullReference可能發生在項目的任何地方。這並不一定意味着你的映射是錯誤的。 – Yorro