Search code examples
c#mongodbmongodb-.net-drivermongorepository

MongoRepository Entity in StateServer


I have an MVC project with a User class that is marked [Serializable].

This User class inherits from MongoRepository's "Entity" class as instructed in the documentation.

However when I try to save an instance of the User class to session, via StateServer, I get an error that the object is not serializable.

I'm new to MongoDB and MongoRepository so I'm not sure if there is something I can do here to make the instance of the user class serializable.

Sample code:

[Serializable]
public class SiteUser : Entity
{
   public string username { get; set; }
}

public ActionResult Index()
{
  MongoRepository<SiteUser> userRepo = new MongoRepository<SiteUser>();
  SiteUser user = userRepo.First(m => m.username == "myusername");
  Session["MyUser"] = user; // This won't work due to the "Entity" link.
  return View();
}

Solution

  • Implement IEntity, the Interface, instead of inheriting from Entity so you aren't depending on the Entity baseclass.

    [Serializable]
    public class SiteUser : IEntity
    {
       public string Id { get; set; }
       public string username { get; set; }
    }
    

    Also, since 1.5.1 the Entity class is also marked as serializable.