C#学习教程:使用BsonRepresentation(BsonType.ObjectId)和BsonIdvs.ObjectId装饰C#中属性的区别我是mongodb的新手,喜欢不必担心架构,我有一个问题,假设您想在mongo中使用Id属性,而mongo使用ObjectId作为属性Id,到目前为止我看到您可以拥有或装饰一个Id如下,publicObjectIdId{get;set;}//或[BsonId]publicstringId{get;set;}//or[BsonId][BsonRepresentation(BsonType.ObjectId)]publicstringId{get;放;}任何人都可以向我解释为什么大多数人选择最后一种类型以及最新的类型以及灵活性如何提供帮助。谢谢?1)如果在强类型TDocument类(集合中的项类型)中有一个名为Id、id或_id的列,则Mongo中将生成一个名为“_id”的列。它还将在该列上创建索引。如果您尝试使用已存在的键插入一个项目,您将得到一个重复键错误异常。公共ObjectIdId{得到;放;}将使用ObjectId的类型生成器,它看起来像_id:ObjectId("57ade20771e59f422cc652d9")。公共Guid_id{得到;放;}将使用Guid生成器生成类似"_id"的内容:BinData(3,"s2Td7qdghywlfMSWMPzaA==")smth"_id":BinData(3,"s2Td7qdghkywlfMSWMPzaA==")。公共intId{得到;放;},公共字符串id{get;放;}publicstringid{get;放;}publicstringid{get;放;},publicbyte[]_id{得到;放;}publicbyte[]_id{得到;放;如果未指定,也将使用每种类型的索引列的默认值。2)[BsonId]使您可以灵活地以任何方式命名索引。[BsonId]publicGuidSmthElseOtherThanId{get;放;}和[BsonId]publicstringStringId{get;放;}[BsonId]publicstringStringId{get;放;}将是索引;publicGuidSmthElseOtherThanId{get;放;}和publicstringStringId{get;放;}公共字符串StringId{得到;放;}将不会。mongodb仍将在内部使用_id。同样的逻辑,publicObjectIdSmthElseOtherThanId{get;设置;}公共ObjectIdSmthElseOtherThanId{get;set;}没有[BsonId]装饰将不是索引列。3)[BsonRepresentation]允许您将Mongo类型与内部.Net类型一起使用,前提是它们之间存在转换。有[BsonId][BsonRepresentation(BsonType.ObjectId)]publicObjectIdId{get;放;}[BsonId][BsonRepresentation(BsonType.ObjectId)]publicObjectIdId{get;放;}[BsonId][BsonRepresentation(BsonType.ObjectId)]publicObjectIdId{get;放;}和publicObjectId{get;放;}公共ObjectIdId{得到;放;}公共ObjectIdId{得到;放;}.拥有[BsonId][BsonRepresentation(BsonType.ObjectId)]publicstringId{get;放;}[BsonId][BsonRepresentation(BsonType.ObjectId)]publicstringId{get;放;然而,是不同的。Mongo自动生成对象id,但是你可以在.net中使用字符串,过滤查询等,因为对象id和字符串之间存在转换。[BsonId][BsonRepresentation(BsonType.ObjectId)]publicbyte[]Id{get;放;}[BsonId][BsonRepresentation(BsonType.ObjectId)]publicbyte[]Id{get;放;}[BsonId][BsonRepresentation(BsonType.ObjectId)]publicbyte[]Id{get;放;}或[BsonId][BsonRepresentation(BsonType.ObjectId)]publicintId{get;放;}[BsonId][BsonRepresentation(BsonType.ObjectId)]publicintId{get;放;}[BsonId][BsonRepresentation(BsonType.ObjectId)]publicintId{get;放;}将失败,ObjectIdnotavalidrepresentationforaByteArraySerializer/Int32Serializer消息放;}[BsonId][BsonRepresentation(BsonType.String)]publicintStringId{get;放;}会没有事的。以上就是C#学习教程:C#中使用BsonRepresentation(BsonType.ObjectId)和BsonIdvs.ObjectId修饰属性的区别。如果对大家有用,需要进一步了解C#学习教程,希望大家多多关照——本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
