6.0: NoteService
6.0: Create the NoteService
NoteServiceThe 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.
Right click on ElevenNote.Services
Add -> Class and name it
NoteService.csMake the class public
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
Right click on ElevenNote.Services and choose Add -> Reference
Select the ElevenNote.Models and ElevenNote.Data projects
We add references so that we can use the models and properties from those projects.
Add the CreateNote() method
CreateNote() methodIn the
NoteService.csfile, add the followingCreateNotemethod within theNoteServiceclass: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; } } } }CTRL .to bring in the using statements.This will create an instance of
Note.
Add the GetNotes() Method
GetNotes() MethodAdd the following
GetNotes()method in theNoteServiceclasspublic 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(); } } } }
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