实体框架代码首先是自我参考问题 [英] Entity framework code first self reference Problem
问题描述
i有一个评论表,其中每条评论都可能有评论类型的回复。
i mean评论表引用自己(我的英语不够好)。
还有一个文章表女巫有一系列评论。
每件事都没问题,记录正确插入数据库购买时我想检索特定评论的儿童评论>>他们是空的! >>
请看一下代码...
这是我的课程:
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...
推荐答案
我发现...
i必须做两个查询:
首先查询获取文章和第二个一个得到评论和回复。
i found that...
i have to do two query:
first query to get article and the second one to get the comments and replies.
这篇关于实体框架代码首先是自我参考问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!