2014-07-19 2 views
0

매핑이있는 3 가지 모델이 있습니다.Many to Many 매핑/시드

문제는 NullReferenceException을받는 시드를 시도 할 때입니다.

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); 
    } 

이 매핑이 정확 :

[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); 
    } 

그리고 이것은 내가 데이터를 종자 방법은? "마이 그 레이션"을 사용할 경우 매번 모든 데이터를 재설정해야합니까?

+0

NullReference는 프로젝트의 어느 곳에서나 발생할 수 있습니다. 반드시 매핑이 잘못되었다는 것을 의미하지는 않습니다. – Yorro

답변

0

답변 해 주셔서 감사합니다.

나는이 문제를 해결했다.

태그는 목록이고 태그를 추가하기 전에 인스턴스를 만드는 것을 잊었습니다.