6.0: NoteService

6.0: Create the NoteService

The service layer is how our application interacts with the database. In this section, we will create the NoteService that will push and pull notes from the database.

  1. Right click on ElevenNote.Services

  2. Add -> Class and name it NoteService.cs

  3. Make the class public

  4. Create a constructor and a private field of type Guid called _userId:

         public class NoteService
         {
             private readonly Guid _userId;
    
             public NoteService(Guid userId)
             {
                 _userId = userId;
             }
         }
     }

Add References

  1. Right click on ElevenNote.Services and choose Add -> Reference

  2. Select the ElevenNote.Models and ElevenNote.Data projects

  3. We add references so that we can use the models and properties from those projects.

Add the CreateNote() method

  1. In the NoteService.cs file, add the following CreateNote method within theNoteService class:

             public bool CreateNote(NoteCreate model)
             {
                 var entity = 
                     new Note()
                     {
                         OwnerId = _userId,
                         Title = model.Title,
                         Content = model.Content,
                         CreatedUtc = DateTimeOffset.Now
                     };
    
                 using (var ctx = new ApplicationDbContext())
                 {
                     ctx.Notes.Add(entity);
                     return ctx.SaveChanges() == 1;
                 }
             }
         }
     }
  2. CTRL . to bring in the using statements.

  3. This will create an instance of Note.

Add the GetNotes() Method

  1. Add the following GetNotes() method in the NoteService class

             public IEnumerable<NoteListItem> GetNotes()
             {
                 using (var ctx = new ApplicationDbContext())
                 {
                     var query = 
                         ctx
                             .Notes
                             .Where(e => e.OwnerId == _userId)
                             .Select(
                                 e =>
                                     new NoteListItem
                                     {
                                         NoteId = e.NoteId,
                                         Title = e.Title,
                                         CreatedUtc = e.CreatedUtc
                                     }
                             );
    
                     return query.ToArray();
                 }
             }
         }
     }
  2. This method will allow us to see all the notes that belong to a specific user.

Next, we'll make some changes in the NoteController.

Last updated