MongoDB中的ObjectID曝光 [英] MongoDB ObjectIds exposure

查看:154
本文介绍了MongoDB中的ObjectID曝光的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个数据层(包含连接的MongoDB),领域层(含回购和实体)和服务层(包含服务和模型)

I have a Data layer (Contains connection to MongoDB), a domain layer (contains repos and entities) and a service layer (contains services and models)

现在因为我的实体使用的ObjectID,他们需要的MongoDB的知识(这是罚款?)

Now because my entities use ObjectIds, they require knowledge of MongoDB (Is this fine?)

我的服务得到调用返回这些实体的存储库,然后将它们转换成模型。这导致我的服务层要求,因为物业的ObjectId对实体的MongoDB的知识。

My services get calls the repositories which returns these entities, and then converts them to models. This is causing my service layer to require knowledge of MongoDB because of the ObjectId Property on the entities.

有没有一种方法可以让我避免这种情况?我听说,我可以用我的ID作为字符串类型和存储数据时,MongoDB的将其转换为一个的ObjectId?

Is there a way I can avoid this? I have heard I can use my Id as type string and when storing the data MongoDB will convert this to a ObjectId?

推荐答案

有时以映射只有ID可以是混乱,在你可能在你的同一个实体有另一个对象ID(可能是引用)的情况下还发生了什么?

Sometimes to mapping only the Id could be confusing and also what happens in the case that you may have another objectId (maybe a reference) in your same entity?

也可以使一个地图的ObjectID使用过配置模式的地图约定。看看下面的实现:

well you can make a map for objectId using a map convention over configuration pattern. look at the following implementation:

public static class MongoDbConventionRegistry
{
    public static void Register()
    {
        var conventionPack = new ConventionPack {new StringObjectIdMemberMapConvention()};            
        ConventionRegistry.Register("CustomConventions", conventionPack, t => t.FullName.StartsWith("YourNamespace.Model.Entities.etc")); 
     }

 }

public class StringObjectIdMemberMapConvention : IMemberMapConvention
{
    private  readonly Regex _memberMatchRegex = new Regex(@"(^Id$)|(.+ObjectId?$)",RegexOptions.Compiled); // you can change this regex to match the convention you want

    public string Name {
            get { return "StringObjectId"; }
        }

        public void Apply(BsonMemberMap memberMap)
        {
            if (memberMap == null)
                return;
            if(memberMap.MemberType == typeof(string) && _memberMatchRegex.IsMatch(memberMap.ElementName) )
                memberMap.SetRepresentation(BsonType.ObjectId);
        }

    }



所以这种情况下,任何标识和与OBJECTID结尾的任何其他属性将被映射到OBJECTID,这样你就可以留下您的实体ID作为字符串,驱动程序会为您处理的转化,这是更方便,当你不希望进行大部分的层之间的MongoDB的相关性在您的系统。

so for this case any Id and any other property that ends with objectId will be mapped into objectId, so you can leave your entities ids as string and the driver will handle the conversion for you, it's more convenient when you don't want carry the mongodb dependencies between most of your layers in your system.

你可以改变你希望该公约的任何,我只是想highight的功能。

you can change the convention to any you want, I just wanted to highight the feature.

这篇关于MongoDB中的ObjectID曝光的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆