0

Is there a way to update fields in the default ASP.NET MVC database directly from a SignalR hub?

As you know, by default on a new MVC template project, Visual Studio creates 3 controllers, Home, Account and Manage. From those 3 it is easy to access the database like this:

using (var con = new ApplicationDbContext())
{
    var userID = UserManager.FindById(User.Identity.GetUserId());
    var userR = con.Users.FirstOrDefault(x => x.Id == userID.Id);

    userR.Wins = 0;
    userR.Loses = 0;
    userR.Ties = 0;

    con.SaveChanges();
}

where UserManager is defined by default like this:

private ApplicationUserManager _userManager;
public ApplicationUserManager UserManager
{
    get
    {
        return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
    }
    private set
    {
        _userManager = value;
    }
}

I am looking for a way to do something like this in my SignalR Hub.

Brendan Green
  • 10,893
  • 5
  • 40
  • 68
geoko93
  • 25
  • 8
  • I think a question would be, why would you want to? You'd use websockets to update the UI in real time, not update the database. However, you *can* call the hub's context if you really feel so inclined. – Drew Kennedy Jun 01 '16 at 11:18
  • well, based on what I receive in the hub from the client side, i want to update a row in the DB. It is not necessary to do it in the hub, but I do not know where. Can you give me an example of how can I call the hub's context? To be more specific. I am implementing a chess game, and when it ends, i want to increase the number of wins/draws/loses that the players have. – geoko93 Jun 01 '16 at 11:21
  • Something like [this](http://stackoverflow.com/a/10914638/4204026) I believe. Not too sure if it's what you're after though. – Drew Kennedy Jun 01 '16 at 11:29
  • I do not want to call a hub method from elsewhere. I will probably call in the hub a method defined somewhere else, that will update my database. – geoko93 Jun 01 '16 at 12:38

2 Answers2

0

As far as I see your main issue is to get current user Id inside hub class to update the record in the database. If so you can try to use:

string userId = Context.User.Identity.GetUserId<string>();

So the final code is going to be:

using (var con = new ApplicationDbContext())
{
    string userId = Context.User.Identity.GetUserId<string>();
    var userR = con.Users.FirstOrDefault(x => x.Id == userId);

    userR.Wins = 0;
    userR.Loses = 0;
    userR.Ties = 0;

    con.SaveChanges();
}

For sure, it is for case where user's Id is of string type

temaby
  • 61
  • 4
0

I think what you are looking for is here: http://www.asp.net/signalr/overview/guide-to-the-api/mapping-users-to-connections

One thing to be aware of is that you have to have signalr authorization configured for this to work.

Kelso Sharp
  • 1,003
  • 8
  • 12