c# - MongoDB自定义映射
问题描述
我正在尝试开发一个具有两个主要域实体的应用程序:Entry
和Category
,并且我将使用 mongodb。我将有一个条目集合和一个类别集合。条目集合可能有成千上万的文档,而类别则有数百个。
在我看来,我想显示所有条目的信息及其类别名称和颜色。我想保留他们的类别 ID,以便在类别名称或颜色发生变化时更新受影响的条目。所以我想要一个这样的文件:
{
"_id": 123456,
"date": '2018-08-15',
"description": "Some entry description"
....
category:
{
"id": 123,
"name": "My category",
"color:" "blue"
}
问题是它Category
有更多的属性,所以我的文档最终是这样的:
{
"_id": 123456,
"date": '2018-08-15',
"description": "Some entry description"
....
category:
{
"id": 123,
"name": "My category",
"color": "blue",
"otherProp": "a",
"anotherProp": "b",
"differentProp": "c"
}
}
我尝试使用BsonClassMap.RegisterClassMap
仅映射Category
for Entry
collection 的某些属性,但这似乎是不可能的。如果我忽略某些Category
属性,类别的集合也不会包含这些被忽略的项目。
我应该像下面这样处理不同的模型表示还是创建新实体来保存我想要的信息(所以我的存储库不会持久Entry
但会持久EntryDataObject
)?
public class Entry {
public string Description { get; set; }
...
public Category Category { get; set; }
}
public class Category {
public string Name { get; set; }
public string Color { get; set; }
}
public class CategoryExtraInformation {
public string OtherProp { get; set; }
public string AnotherProp { get; set; }
public string DifferentProp { get; set; }
public Category Category { get; set; }
}
解决方案
我现在面临着类似的问题。装饰器(即 [Ignore])也没有正确解决我的用例,因为它们会影响使用该类的所有地方。
我正在使用的解决方案是提供帮助函数(和/或构造函数)来创建具有适当属性子集的类。
例如,设置一个构造函数来构建一个新对象,该对象仅包含嵌入式实例所需的属性……假设您有一个名为 category 的 Category 类的“完整”实例。您现在想要更新或创建一个 Entry 实例。如果您有一个有限范围的构造函数
public Category(int ID, string name, string color)
{
id = ID;
Name = name;
Color = color
}
然后,您可以调用它来创建一个新的 Category 对象,该对象具有如下有限字段:
var categoryLimited = new Category(category.id, category.Name, category.Color);
现在使用 categoryLimited 在 Mongo 中执行保存或更新操作。MongoDB 记录将仅包含所需的属性。显然,这种方法将仅限于在“额外属性”中没有默认值或强制字段的类。
祝你好运!
推荐阅读
- c# - 在设计器中打开自定义用户控件时,Visual Studio Professional 15.9.2 崩溃
- java - ArrayList 对象按整数排序
- python - 如何使用熊猫转换这个文件?
- c - 较大值的错误动态内存分配
- java - JAVA - 如何将 Spring Boot 应用程序与 SQL Server 2016(具有 Windows 身份验证)连接?
- javascript - Google Apps 脚本库和脚本分发
- javascript - 如何将不和谐登录添加到 Chrome 扩展程序
- html - CSS 背景图像不会加载 Django 2.1.2
- r - ggplot中的直方图
- c - 程序不起作用可能导致分段错误