Hi,
i have a Comment Table where every comment may have replies of type Comment.
i mean Comment Table is referencing its self(my english isnt good enough).
also there is an Article table witch has a collection of comments.
every thing is ok and records are inserted correctly into database buy when i want to retrieve child comments of a specific comment >> they`r null !! >>
take a look at code please...
here is my classes:
public class Comment
{
public Comment()
{
this.Replies = new HashSet<Comment>();
}
public long Id { get; set; }
public string Title { get; set; }
public ICollection<Comment> Replies { get; set; }
public long? ArticleId { get; set; }
public Article Article { get; set; }
}
public class Article
{
public Article()
{
this.Comments = new HashSet<Comment>();
}
public long Id { get; set; }
public string Title { get; set; }
public ICollection<Comment> Comments { get; set; }
}
and the context:
public class CommentContext : DbContext
{
public CommentContext()
: base("Default")
{
}
public DbSet<Article> Articles { get; set; }
public DbSet<Comment> Comments { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Article>()
.HasMany(a => a.Comments)
.WithOptional(c => c.Article)
.HasForeignKey(c => c.ArticleId);
base.OnModelCreating(modelBuilder);
}
}
every thing is ok and records are inserted correctly into database with this code:
CommentContext db = new CommentContext();
Article article = new Article() { Title = "Intro to .NET" };
Comment comment = new Comment() { Title = "Main Comment" };
comment.Replies.Add(new Comment() { Title = "Child comment 1" });
comment.Replies.Add(new Comment() { Title = "Child comment 2" });
article.Comments.Add(comment);
db.Articles.Add(article);
db.SaveChanges();
but i cant retrive child comments of a comment , here is the code for that:
Article article = db.Articles.Include("Comments").SingleOrDefault();
foreach (var comment in article.Comments)
{
Console.WriteLine("Parent Comment: " + comment.Title);
foreach (var reply in comment.Replies)
{
Console.WriteLine(reply.Title);
}
}
cant see the replies of the comment..
thanks alot...