【问题标题】:Simple Persistence in RavenDBRavenDB 中的简单持久化
【发布时间】:2013-10-23 13:41:52
【问题描述】:
public class BlogPost
{
    public string Id { get; set; }
    public string Title { get; set; }
    public string Category { get; set; }
    public string Content { get; set; }
    public DateTime PublishedAt { get; set; }
    public string[] Tags { get; set; }
    public BlogComment[] Comments { get; set; }
}

public class BlogComment
{
    public string Id{get;set;}
    public string Title { get; set; }
    public string Content { get; set; }
}

BlogPost post = new BlogPost()
                {
                    Title = "Hello RavenDB",
                    Category = "RavenDB",
                    Content = "This is a blog about RavenDB",
                    Comments = new BlogComment[]
                                {
                                    new BlogComment() {Title = "Unrealistic", Content = "This example is unrealistic"},
                                    new BlogComment() {Title = "Nice", Content = "This example is nice"}

                                }
                };

坚持这将导致 BlogComment 字段被嵌入到 BlogPost 文档中

RavenDB 不会为 BlogComment 字段生成 Id

我真正想要的是 BlogPost 只保留对 BlogComment 字段的引用,并将 BlogComment 实例存储为单独的实体

任何提示都可以

谢谢。我必须进行编辑以正确代表我的困境

【问题讨论】:

    标签: asp.net-mvc-4 c#-4.0 ravendb


    【解决方案1】:

    RavenDB 不是关系型数据库,因此,如果您希望在对象关系方面获得与 SQL 相同的行为,那么您将会遇到非常糟糕的情况。根据您的编辑,您需要将 Comment 存储为具有自己的 string Id 属性的单独实体。然后您可以将其存储在 BlogPost 对象的属性中。但是,您真的不想每次有人添加评论时都更新BlogPost 文档,因此更好的解决方案是将BlogPost 的ID 存储在Comment 对象上,因为它正确地代表了关系和正确使用文档模型。然后您将加载一个BlogPost 和所有基于BlogPost ID 的所有Comment 文档。

    【讨论】:

    • 这不是为博客 cmets 建模的唯一方法 - 例如,请参阅 RaccoonBlog 是如何做到的
    • @synhershko 如果你能指出软件开发中任何问题的“唯一方法”,我会给你100美元。我很简单地给了他一个解决方案,这对于显然刚刚学习 Raven 的人来说是一个很好的步骤。至于 Ayende,嗯,他对任何给定问题的解决方案都会根据他有多少 shepards 馅饼而变化(这是个人经验轶事)
    【解决方案2】:

    类似这样(RavenDB 中的文档 ID 是字符串,因此引用也是):

    public class Ex1
    {
      public string Ex2Id {get;set;}
    }
    

    只要确保您以面向文档的心态正确地建模事物,而不是试图模仿关系行为

    【讨论】:

      猜你喜欢
      • 2011-12-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-04
      • 2014-12-01
      相关资源
      最近更新 更多