ska*_*kin 4 c# inversion-of-control mongodb
使用MongoDB作为我的数据存储使我默认将ObjectID类型作为主键.它也可以通过使用Guid和[BsonId]属性来更改.这也是在MongoDB C#驱动程序库中定义的.我想让我的实体独立于数据层.我可以只使用名称ID来识别主键吗?我还能尝试什么?
Pet*_*ter 10
您可以使用BsonClassMap而不是使用属性来保持您的类"干净".
// 'clean' entity with no mongo attributes
public class MyClass
{
public Guid Id { get; set; }
}
// mappings in data layer
BsonClassMap.RegisterClassMap<MyClass>(cm =>
{
cm.AutoMap();
cm.MapIdMember(c => c.Id).SetIdGenerator(CombGuidGenerator.Instance);
});
Run Code Online (Sandbox Code Playgroud)
[BsonId] 属性用于指示 _id 属性应链接到特定属性。没有办法解决这个问题(在你的 crud 操作中完全忽略 _id 这似乎是一个坏主意)。
因此,如果您想将“实体”对象与“数据层”分开,那么只需使用 poco 类。
-- 使用poco 类代替记录。 该类仅用于数据存储:一种将数据输入/输出 mongo 的快速方法,也是处理 bson 文档的绝佳替代方案。
- 在实体层的 poco 类之上使用外观。我觉得重新发明轮子没有用,所以我通常会要求我们的开发人员让实体接口继承数据层 (poco) 接口,但您可以随心所欲地进行
IMyObjectRecord(在 dal 中声明并且只包含属性和 mongo 特定的属性)
IMyObject:IMyObjectRecord(在实体级别声明,可能包括添加的属性和方法)
MyObjectRecord:IMyObjectRecord(在 dal 中声明,包含 mongo 特定的属性。如果您想对分离非常严格,可以声明为 internal)。
MyObject:IMyObject(例如,可以是您从 dal 中提取的 IMyObjectRecord 类顶部的外观)。
现在 - 您获得了外观的所有好处,并且在属性之间有一个硬编码的链接,但是,您可以将 Bson 属性包含在您的 dal 中。
是的。我可以接受。 好的,那么公约包怎么样? 如果你绝对承诺你会调用你的 Id 的“Id”并且你发誓你将它们作为字符串输入(或者 - 使用一些其他易于识别的约定),那么我们可以使用像这样的约定包我从这里偷的
namespace ConsoleApp {
class Program {
private class Foo {
// Look Ma! No attributes!
public string Id { get; set; }
public string OtherProperty { get; set; }
}
static void Main(string[] args) {
//you would typically do this in the singleton routine you use
//to create your dbClient, so you only do it the one time.
var pack = new ConventionPack();
pack.Add(new StringObjectIdConvention());
ConventionRegistry.Register("MyConventions", pack, _ => true);
// Note that we registered that before creating our client...
var client = new MongoClient();
//now, use that client to create collections
var testDb = client.GetDatabase("test");
var fooCol = testDb.GetCollection<Foo>("foo");
fooCol.InsertOne(new Foo() { OtherProperty = "Testing", Id="TEST" });
var foundFoo = fooCol.Find(x => x.OtherProperty == "Testing").ToList()[0];
Console.WriteLine("foundFooId: " + foundFoo.Id);
}
//obviously, this belongs in that singleton namespace where
//you're getting your db client.
private class StringObjectIdConvention : ConventionBase, IPostProcessingConvention {
public void PostProcess(BsonClassMap classMap) {
var idMap = classMap.IdMemberMap;
if (idMap != null && idMap.MemberName == "Id" && idMap.MemberType == typeof(string)) {
idMap.SetIdGenerator(new StringObjectIdGenerator());
}
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
这是在序列化/反序列化期间应用的一小套 mongo“规则”。您注册一次(在设置引擎时)。在这种情况下,示例包告诉 mongo“如果您看到名为 'Id' 的字段,请将其保存为 _id 的字符串。”
这些会变得非常复杂和有趣。如果你真的真的很讨厌另一种方法,我会深入研究会议包。这是将所有 mongo“属性驱动”逻辑强制到一个独立位置的好方法。
| 归档时间: |
|
| 查看次数: |
2404 次 |
| 最近记录: |