在 mongodb 和 Entityframework 中使用相同的 C# Poco 类
Using same C# Poco classes with in mongodb and Entityframework
我的域名类如下:
public class Author
{
public int Id { get; set; }
public string Name { get; set; }
public IList<Post> Posts { get; set; }
}
public class Blog
{
public int Id { get; set; }
public string Name { get; set; }
public IList<Post> Posts { get; set; }
}
public class Post
{
public int Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public Author Author { get; set; }
public Blog Blog { get; set; }
}
如您所见,我绝对没有 entity framework 注释的任何数据注释或属性,我在另一个 class 中为每个使用 [=23] 配置 Entity framework 相关注释=] 流利 api。
现在我想用 MangoDb 替换 entity framework。
但在 mongo 数据库中,我需要在列表中放置一个属性,如下所示:
public class Author
{
[BsonElement("_id")]
[BsonRepresentation(BsonType.ObjectId)]
public int Id { get; set; }
public string Name { get; set; }
public IList<Post> Posts { get; set; }
}
我的问题是有没有办法在另一个 class 外部进行此配置,并且不要像我们在 entity framework 的流利中那样触摸我的 poco classes api。
基本上您可以同时使用 EntityFramework 和 MongoDB 驱动程序属性。但我不建议您使用与 EntityFramework 中使用的完全相同的数据结构,因为 SQL 和 NoSQL 是完全不同的方法。使用 NoSQL,您应该更多地考虑您的应用程序将如何使用您的数据并创建您的域,选择最佳嵌入策略并相应地应用索引。
您可以在 MongoDB 网站上找到一些不错的读物。这里有一些链接可以开始:
http://docs.mongodb.org/manual/core/data-model-design/
http://docs.mongodb.org/manual/core/data-modeling-introduction/
您可以使用 BsonClassMap class 来做到这一点,例如:
BsonClassMap.RegisterClassMap<Post>(cm =>
{
cm.MapMember(x => x.Title).SetElementName("_title");
});
文档在这里:Mapping Classes
还有默认约定,对于 Id 字段你不需要将它映射到 _id name,它会自动处理。
我的域名类如下:
public class Author
{
public int Id { get; set; }
public string Name { get; set; }
public IList<Post> Posts { get; set; }
}
public class Blog
{
public int Id { get; set; }
public string Name { get; set; }
public IList<Post> Posts { get; set; }
}
public class Post
{
public int Id { get; set; }
public string Title { get; set; }
public string Content { get; set; }
public Author Author { get; set; }
public Blog Blog { get; set; }
}
如您所见,我绝对没有 entity framework 注释的任何数据注释或属性,我在另一个 class 中为每个使用 [=23] 配置 Entity framework 相关注释=] 流利 api。 现在我想用 MangoDb 替换 entity framework。
但在 mongo 数据库中,我需要在列表中放置一个属性,如下所示:
public class Author
{
[BsonElement("_id")]
[BsonRepresentation(BsonType.ObjectId)]
public int Id { get; set; }
public string Name { get; set; }
public IList<Post> Posts { get; set; }
}
我的问题是有没有办法在另一个 class 外部进行此配置,并且不要像我们在 entity framework 的流利中那样触摸我的 poco classes api。
基本上您可以同时使用 EntityFramework 和 MongoDB 驱动程序属性。但我不建议您使用与 EntityFramework 中使用的完全相同的数据结构,因为 SQL 和 NoSQL 是完全不同的方法。使用 NoSQL,您应该更多地考虑您的应用程序将如何使用您的数据并创建您的域,选择最佳嵌入策略并相应地应用索引。
您可以在 MongoDB 网站上找到一些不错的读物。这里有一些链接可以开始:
http://docs.mongodb.org/manual/core/data-model-design/
http://docs.mongodb.org/manual/core/data-modeling-introduction/
您可以使用 BsonClassMap class 来做到这一点,例如:
BsonClassMap.RegisterClassMap<Post>(cm =>
{
cm.MapMember(x => x.Title).SetElementName("_title");
});
文档在这里:Mapping Classes
还有默认约定,对于 Id 字段你不需要将它映射到 _id name,它会自动处理。