How to pass ObjectId from MongoDB in MVC.net

后端 未结 5 469
野的像风
野的像风 2020-12-06 11:55

I\'m starting a new project with Mongo, NoRM and MVC .Net.

Before I was using FluentNHibernate so my IDs were integer, now my IDs are ObjectId. So when I have an Edi

5条回答
  •  半阙折子戏
    2020-12-06 12:37

    I Use following

    public class ObjectIdModelBinder : DefaultModelBinder
    {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            string value = controllerContext.RouteData.Values[bindingContext.ModelName] as string;
            if (String.IsNullOrEmpty(value)) {
                return ObjectId.Empty;
            }
            return new ObjectId(value);
        }
    }
    

    and

    protected void Application_Start()
        {
            ......
    
            ModelBinders.Binders.Add(typeof(ObjectId), new ObjectIdModelBinder()); 
        }
    

    almost forgot, make URLs from ObjectId.ToString()

提交回复
热议问题