Session is null (Object reference not set to instance of reference)

512 views
Skip to first unread message

Wasfa Anjum

unread,
Mar 7, 2014, 11:31:58 AM3/7/14
to rav...@googlegroups.com

I am using RavenDB with asp.net MVC4 application.I have a method in my model in  which i called database
I have also called this method in controller which is inherited from my RaenController.
But IDocumentSession object is null in model.
Any one help me to fix the problem of null session object in model.

Kijana Woodard

unread,
Mar 7, 2014, 11:46:03 AM3/7/14
to rav...@googlegroups.com
"I have a method in my model"
Ummm. What? Why?

For the rest, show code. 
Using a container?


--
You received this message because you are subscribed to the Google Groups "RavenDB - 2nd generation document database" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ravendb+u...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Wasfa Anjum

unread,
Mar 7, 2014, 11:50:51 AM3/7/14
to rav...@googlegroups.com
I want to check that a vehicle exists in db ,for this purpose i have a method.
 public bool VehicleExist(Vehicle vec)
        {
            bool success = false;
            string userName = "65fa4b2c-14f1-4863-b509-f36ab0a99c0e";

            var vehicleExist = from vehc in Session.Query<Vehicle>()
                               where vehc.registartion == vec.registartion
                               where vehc.userId==userName
                               select vehc;
            if (vehicleExist.Count() > 0)
            {
                success = true;
            }

            return success;
        }
which is in my model class.I have called this method in controller.when i debuged the code it throws an exception object reference not set to an instance of reference at this line  var vehicleExist = from vehc in Session.Query<Vehicle>(), as i told that Session is null which is the object of IDocumentSession 




--
You received this message because you are subscribed to a topic in the Google Groups "RavenDB - 2nd generation document database" group.
To unsubscribe from this topic, visit https://groups.google.com/d/topic/ravendb/VkBCAGzuaPE/unsubscribe.
To unsubscribe from this group and all its topics, send an email to ravendb+u...@googlegroups.com.

Kijana Woodard

unread,
Mar 7, 2014, 12:21:16 PM3/7/14
to rav...@googlegroups.com
How does Session get set in your model.

Fwiw, it's not a good idea to query from your models.

Chris Marisic

unread,
Mar 7, 2014, 1:57:33 PM3/7/14
to rav...@googlegroups.com
Replace not good idea, with flat out wrong. 

Wasfa Anjum

unread,
Mar 8, 2014, 1:05:57 AM3/8/14
to rav...@googlegroups.com
I am confused that should i call datbase query in controller which is extended from base controller where session is get set.because model
cannot be derived from base raven controller.This is reason that session is null in model.

public class VehicleController : RavenController
    {
  [HttpPost]
        public ActionResult AddVehicle(Vehicle vehicleModel)
        {  if (ModelState.IsValid)
            {

              
                string userName = "65fa4b2c-14f1-4863-b509-f36ab0a99c0e";

                bool success = vehicleModel.VehicleExist(vehicleModel);
                if(success)
                {


                    string vehicleKey = vehicleModel.AddVehicle(vehicleModel,userName);
                    if (vehicleKey != null)
                    {
                        ModelState.AddModelError("", "Your vehicle has been added successfully!");
                    }

                    else
                    {
                        ModelState.AddModelError("", "Vehicle is not added");
                    }
                }

                ModelState.AddModelError("", "Vehicle already exist");

            }
            else
            {
                ModelState.AddModelError("", "Please correct the errors to continue");
            }
           

            
            return View();
        }

Model
  public class Vehicle
    {

        public IDocumentStore _documentStore;
        public new IDocumentSession Session { get; set; }


        public string vehicleId { get; set; }
        public string userId { get; set; }
        public string SelectedVehicleType { get; set; }
        [Required(ErrorMessage = "Please select Vehicle Type")]
        public string vehicleType { get; set; } //drop down list
        [Required(ErrorMessage = "Please Enter Vehicle Make")]
        public string make { get; set; }
        [Required(ErrorMessage = "Please select Vehicle Model")]
        public string modelType { get; set; }
        [Required(ErrorMessage = "Please select Vehicle Color")]
        public string color { get; set; }
        [Required(ErrorMessage = "Please Enter Vehicle Registration Number")]
        public string registartion { get; set; }

  public bool VehicleExist(Vehicle vec)
        {
            bool success = false;
            string userName = "65fa4b2c-14f1-4863-b509-f36ab0a99c0e";

            var vehicleExist = from vehc in Session.Query<Vehicle>()
                               where vehc.registartion == vec.registartion
                               where vehc.userId==userName
                               select vehc;
            if (vehicleExist.Count() > 0)
            {
                success = true;
            }

            return success;
        }

RavenController
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Raven.Client;
using Raven.Client.Document;

namespace ParkOnMyDrive.Controllers
{
    public class RavenController : Controller
    {
         public class AccountController : Controller
        {

            public readonly IDocumentSession session;

            public AccountController(IDocumentSession session)
            {
                this.session = session;
            }

        }


        public class ProfileManagementController : Controller
        {
            private readonly IDocumentSession session;

            public ProfileManagementController(IDocumentSession session)
            {
                this.session = session;
            }
        }



        public class VehicleController : Controller
        {

            public readonly IDocumentSession session;

            public VehicleController(IDocumentSession session)
            {
                this.session = session;
            }

        }





        public new IDocumentSession Session { get; set; }
        private static IDocumentStore documentStore;


        public static IDocumentStore DocumentStore
        {
            get
            {

                if (documentStore != null)

                    return documentStore;

                lock (typeof(RavenController))
                {
                    if (documentStore != null)
                        return documentStore;

                    documentStore = new DocumentStore
                    {

                        ConnectionStringName = "RavenDB"
                    }.Initialize();
                }

                return documentStore;

            }
        }//get 

        protected override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            Session = DocumentStore.OpenSession("RavenMemberShip");
        }

        protected override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            using (Session)
            {
                if (Session != null && filterContext.Exception == null)
                    Session.SaveChanges();
            }
        }




    

    }
}

       



Wayne Douglas

unread,
Mar 8, 2014, 4:33:19 AM3/8/14
to rav...@googlegroups.com
Having a session in a view model is ok.

Having any dependency in your model is a recipe for disaster.

Mircea Chirea

unread,
Mar 8, 2014, 5:51:31 PM3/8/14
to rav...@googlegroups.com
inline


On Saturday, March 8, 2014 11:33:19 AM UTC+2, Wayne Douglas wrote:
Having a session in a view model is ok.

What?! The view model should be a dumb class. It should NEVER, under ANY circumstances, issue a query.
 

Having any dependency in your model is a recipe for disaster.

The model is the logic. Business logic, database logic, etc. It will have dependencies.

Model != Raven documents

Wayne Douglas

unread,
Mar 9, 2014, 3:07:42 AM3/9/14
to rav...@googlegroups.com
Why - on earth - is having a session inside a viewmodel bad?!

Do you understand why having a dependency inside a domain model is bad? Or are you just preaching what you've been preached?

Sent from Mailbox for iPhone


--

Mircea Chirea

unread,
Mar 9, 2014, 6:31:17 AM3/9/14
to rav...@googlegroups.com
The view should never cause a query to a database. That's the model's job; otherwise you have no clean separation of concerns and you end up like PHP.

This is ASP.net MVC, not MVVM.

Jahmai Lay

unread,
Mar 9, 2014, 7:10:56 AM3/9/14
to rav...@googlegroups.com

I wouldn't have database access in the ViewModel in MVVM either, that belongs on the model, even if your model is just a domain-language wrapper around Raven.

Wayne Douglas

unread,
Mar 9, 2014, 8:38:18 AM3/9/14
to rav...@googlegroups.com
Mvvm often has services injected into the viewmodel!

This is just purist nonsense. 

You don't do this in your model in most DDD style systems because of serialization concerns and to maintain persistence ignorance. If you are doing this in your model then you are likely following the Active Record pattern. 

Give me one valid reason a viewmodel can't have a service injected into it. There is no issue with a view model hydrating itself.

Sent from Mailbox for iPhone


Kijana Woodard

unread,
Mar 9, 2014, 11:51:48 AM3/9/14
to rav...@googlegroups.com
STIP: we're straying pretty far from the OP, but since the OP hasn't responded in a while, I'll engage.

Since I have no sense of the sacred with regards to technology, I'll run with you here.

Assume you have some concepts in your code called Models, Views, View Models, and Controllers. If the View Models hydrate themselves from persistence, what is happening in the Controllers? What role do the Models have?

Since getting a View Model from a, *cough*, container would be awkward, it appears that the Controller takes on the role of a low grade DI component to hand out sessions, et al. [fwiw, this is the piece the OP is missing - hand the session to the model].

If you are going to have the View Models construct themselves, why bother calling them View Models? That seems to muddy the water.

I have, myself, written code in which the view model hydrates itself. It seemed like it was working at first. I stopped doing it because it became painful.

What we end up with is a situation in which every request is a new adventure and persistence calls are happening in several different places. Reasoning about behavior becomes hard. Optimization becomes really hard.

Where I agree with you is that *something* needs to completely understand the needs of the view *and* the capabilities of the persistence technology.

Side note: I have become allergic to di containers, hence the cough. Maybe that should have been a sneeze. ;-]





--
You received this message because you are subscribed to the Google Groups "RavenDB - 2nd generation document database" group.
To unsubscribe from this group and stop receiving emails from it, send an email to ravendb+u...@googlegroups.com.

Mircea Chirea

unread,
Mar 9, 2014, 12:54:50 PM3/9/14
to rav...@googlegroups.com
inline


On Sunday, March 9, 2014 2:38:18 PM UTC+2, Wayne Douglas wrote:
Mvvm often has services injected into the viewmodel!

The OP is using ASP.net MVC. MVC != MVVM. You have the controller for a reason.
 
This is just purist nonsense. 

No it isn't. ASP.net was NOT designed with queries in mind from the view. Here, tell me how you can issue a query using IAsyncDocumentSession from the view, as they don't support the TPL. Or use the new HttpClient, which is fully async. In MVC, the view takes a dumb model (called view model) and turns it into some output; that model has everything it needs alredy calculated in the controller.
 

You don't do this in your model in most DDD style systems because of serialization concerns and to maintain persistence ignorance. If you are doing this in your model then you are likely following the Active Record pattern. 

No, it's not active record. You have different layers/services: the database layer, the business layer, the controller layer, the view layer. Each has its own models - they are separate and have different concerns and structures. The models of the DB layer can and probably are completely different from the models in the business layer.

In my case I have to load 4-5 documents to create a single object which contains the business logic and the relevant data. Then the controller will take that fat object (the "model" in MVC) and extract whatever is needed from it to complete the current action; it then passes that small part to the view so it can be rendered.

In MVC, the model is the combination of the business/database/whatever, which hold all your logic, handles persistence, etc. It is not a single class - it is an idea. It usually is a bunch of different libraries each doing its own job. The view model is just the part needed to display the web page, denormalized, with no functionality - a POD.
 
Give me one valid reason a viewmodel can't have a service injected into it. There is no issue with a view model hydrating itself.

  • async
  • separation of concerns
Tell me, when something goes wrong, how are you going to debug it? Your HTML pages are firing queries to the database, transforming the raw database results into an intermediate state, applying some business logic, then transforming that into HTML. Seems a lot like Wordpress and Drupal. Why use MVC then? Why don't just use plain .cshtml files (AKA ASP.NET Web Pages)?

Mircea Chirea

unread,
Mar 9, 2014, 12:59:05 PM3/9/14
to rav...@googlegroups.com
inline


On Sunday, March 9, 2014 5:51:48 PM UTC+2, Kijana Woodard wrote:
Assume you have some concepts in your code called Models, Views, View Models, and Controllers. If the View Models hydrate themselves from persistence, what is happening in the Controllers? What role do the Models have?

Yes, my point exactly.
 
Since getting a View Model from a, *cough*, container would be awkward, it appears that the Controller takes on the role of a low grade DI component to hand out sessions, et al. [fwiw, this is the piece the OP is missing - hand the session to the model].

If you are going to have the View Models construct themselves, why bother calling them View Models? That seems to muddy the water.

I have, myself, written code in which the view model hydrates itself. It seemed like it was working at first. I stopped doing it because it became painful.

That is what you have to do with MVVM; in .NET WPF follows that model, but even then, the VM isn't dependent on other services directly; it just depends on a MODEL; the controller is removed because it wouldn't do anything useful (there is no request lifecycle like in ASP).
 
What we end up with is a situation in which every request is a new adventure and persistence calls are happening in several different places. Reasoning about behavior becomes hard. Optimization becomes really hard.

PHP soup.

Wayne Douglas

unread,
Mar 9, 2014, 1:09:02 PM3/9/14
to rav...@googlegroups.com
Can't really reply as I'm out and about but quickly: someone else mentioned mvvm, I was responding to that. 

Viewmodels aren't restricted to web. I use view models when I'm building an api. An endpoint is a view.

I think we're talking about using view models in different ways. I'm talking about allowing a viewmodel to hydrate itself on instantiation inside the controller, you're talking about hydrating it from within the view.

Fwiw I'm not saying this is how it should be done but there is an argument for it.

Finally, I'm using mvvmcross a lot for x platform mobile dev, this is my only use of mvvm in anger and the standard here is to inject services into vm. It works. So far it's not been a pain point. Which makes me believe even more, this isn't the source of all evil. 

Sent from Mailbox for iPhone


Kijana Woodard

unread,
Mar 9, 2014, 2:18:16 PM3/9/14
to rav...@googlegroups.com

It leads to pain in asp.net mvc.

I can't comment on how it would work in an environment that _wants_ to do mvvm.

Asp.net mvc doesn't want to do mvvm.

Fwiw, I've listened to many a rails dev bemoan the perils of active record.

Wayne Douglas

unread,
Mar 9, 2014, 2:22:28 PM3/9/14
to rav...@googlegroups.com
Active record is (IMO) for novice developers but I'm sure there's usages for it. Prototyping etc

Sent from Mailbox for iPhone


Kijana Woodard

unread,
Mar 9, 2014, 2:50:08 PM3/9/14
to rav...@googlegroups.com

There are probably lots of low value situations in every system that is best disposed of with active record / crud scaffolding. I've used such for things like admin settings.

Jahmai Lay

unread,
Mar 9, 2014, 10:23:57 PM3/9/14
to rav...@googlegroups.com

Speaking about MVVM:

Your ViewModel has a singular purpose, to bind your View and your Model.
If you hydrate your ViewModel directly from a database and call dependent services, then it is taking on the role of the Model.
Sometimes it is awkward to create a Model outside of/before a ViewModel, depending on the UI framework you are using, so you have to work with what you have (Xamarin iOS is a good example of this, as there is no DI available), and whether you are View-first or ViewModel-first, but the pattern of separation is still relevant.
In my case under Xamarin iOS, often my ViewControllers will create Models for their own purpose, simply because there is no way to inject the model in a clean way (unless you threw away all the built in iOS navigation paradigms and composed everything manually), but the Model still exclusively interacts with the service and data layers of my application.

A Model contains all the use-case actions that your application context needs. It could have methods to list, create and delete users from a database. It could do caching. It could be an event provider. It could sit on top of a 3rd party service which provides an XML/Json stream and transform them into domain objects. It might do all these things by sitting on top of other interfaces, but that is another level of abstraction which is outside of the MVVM scope. However, if you are doing any of these things in your ViewModel, then I would suggest that you aren't actually following MVVM, which isn't a problem at all, as you should choose the paradigm that best suits your team and application.

ActiveRecord pattern is quite a different concept to MVVM, and is based on persistence being completely transparent to the business layer. Setting a property potentially writes to the database (either automatically, or after calling Save()), reading a property may load related records, and the class itself somehow (either logically or physically) maps to a record in a database.

I fairly recently worked on a project where an IUnityContainer was passed to every ViewModel in the entire project, and it was up to the ViewModel to Resolve<>() what it needed, so I have experience with the extreme philosophical opposite of what I currently practice.

Wayne Douglas

unread,
Mar 10, 2014, 3:15:29 AM3/10/14
to rav...@googlegroups.com
As a side, check out tinyioc - pretty good di for xam :)

Sent from Mailbox for iPhone


Justin A

unread,
Mar 10, 2014, 7:30:51 PM3/10/14
to rav...@googlegroups.com

someone said..


and i thought...


but then realised that ain't no joke! so ...





I guess i need to take a deep breath and start my morning over again...





:(

Reply all
Reply to author
Forward
0 new messages