RavenDB:如何在嵌入式文档时以不同方式序列化类

时间:2012-10-20 00:07:44

标签: ravendb

RavenDB附带的示例数据库包含Albums文档集合,每个文档集合中都嵌入了Genre文档,如下所示:

{
  ... other stuff...
  "Genre": {
    "Id": "genres/1",
    "Name": "Rock"
  },
  ... other stuff...
}

请注意,此处Genre包含IdName个字段。

但是当您查看Genre个文档时,他们会有IdNameDescription个字段,如下所示:

{
  "Description": "Rock and Roll is a form of rock music developed in the 1950s and 1960s. Rock music combines many kinds of music from the United States, such as country music, folk music, church music, work songs, blues and jazz.",
  "Name": "Rock"
}

我如何在代码中进行建模,以便在Store()然后SaveChanges()时保存自己的文档时将Genre序列化并以不同方式保存(如示例数据)保存Album文档并嵌入Genre

1 个答案:

答案 0 :(得分:3)

此模型将匹配ravendb样本数据:

public class Genre
{
    public string Id { get; set; }
    public string Description { get; set; }
    public string Name { get; set; }
}

public class Album
{
    public string Id { get; set; }
    public string AlbumArtUrl { get; set; }
    public GenreRef Genre { get; set; }
    public decimal Price { get; set; }
    public string Title { get; set; }
    public int CountSold { get; set; }
    public ArtistRef Artist { get; set; }

    public class GenreRef
    {
        public string Id { get; set; }
        public string Name { get; set; }
    }

    public class ArtistRef
    {
        public string Id { get; set; }
        public string Name { get; set; }
    }
}

使用示例包括:

var albumId = "albums/1";
var album = session.Include<Album>(x => x.Genre.Id)
                   .Load<Album>(albumId);
var genre = session.Load<Genre>(album.Genre.Id);

include意味着在加载Genre时,没有db调用,因为它已在会话中被跟踪。