Home > Enterprise >  Question regarding saving entity to database
Question regarding saving entity to database

Time:03-08

Lets say I have a method like:

 public string SetSessionData(dynamic data, string token)
 {
        var request = (data as JObject).ToObject<SetRunSessionDataRequest>();

        var session = runSessionRepository.GetRunSessionWithToken(token);

        if (!string.IsNullOrEmpty(request.Id))
            session.Id = request.Id;

And then I want to save the changes in the repository class, how is that done? will this work?

public string SetSessionData(dynamic data, string token)
{
     var request = (data as JObject).ToObject<SetRunSessionDataRequest>();
    
     var session = runSessionRepository.GetRunSessionWithToken(token);
    
     if (!string.IsNullOrEmpty(request.Id))
        session.Id = request.Id;
            
      runSessionRepository.saveSession(session);

Where the saveSession method in the repository class looks like this:

public void saveSession(session){ 
Session _session = session;
db.saveChanges();
}

So what I'm really asking is how do make the save in the repository class as I don't have a DB instance in the service class and do I even need to send the session variable? It feels pointless but if I don't how does it know what to save? Will it even save anything?

CodePudding user response:

I'm assuming db is your DbContext in your repository, to save your Session object you need to call db.Update(session); before calling db.SaveChanges(); so that EF Core can track the changes and save them when SaveChanges is called.

For example:

public void SaveSession(session){ 
    db.Update(session);
    db.SaveChanges();
}

This article might help explain the pattern it looks like your code is using and why you would want to use it.

  • Related