Learn how to add Entity Framework Core to your project and write basic queries
- Create a new class library project in the solution called
PetStore.Data
. Add a project reference from thePetStore
project to thePetStore.Data
. - Add the nuget package
Microsoft.EntityFrameworkCore.Sqlite
to that project. - Create a new class called
ProductContext
. Use this link to guide you through setting up yourDbContext
class. Feel free to either move the Product class or make a new class calledProductEntity
. Either way,Product
will need to have a property calledProductId
. - Run these commands to create your database. I would advise following the PowerShell commands instead of the Visual Studio ones.
- In the
PetStore.Data
project, add a class calledProductRepository
and add an interface for it. - In the constructor of that class, create a new instance of
ProductContext
and assign it to aprivate
readonly
variable. - Add a method to add a product to the database. Don't forget to call the
SaveChanges
method. - Add a method to get a product by it's id.
- Add a method to get all products from the database.
- Add the repository class to the services like you did with the
ProductLogic
class. - In the
ProductLogic
class. Add aprivate
readonly
variable with the type being the interface for your repository class. Add an argument to the constructor of the logic class of the type of the interface for your repository class. Assign the argument to the private variable. - Replace the
AddProduct
code with a call to your repositories add method. - Change the
GetProductByName
method to no longer be generic, and change it's name to beGetProductById
. Replace the contents of the method with a call to your repositories get method.
At this point, your application will probably have a bunch of errors. That's fine, we'll go ahead and clean those up before testing the database. Remove the following:
- DogLeash class
- CatFood class
- DryCatFood class
- The products list and both dictionaries from ProductLogic.
- GetOnlyInStockProducts from ProductLogic
- GetTotalPriceOfInventory from ProductLogic
Change the following:
- Update the validator to validate products now. Add that to your ProductLogic add method.
- Update the program class to work with the new logic class. You can remove options 3 and 4 completely.
- There will probably be some errors in using statements to clean up at this point too, so feel free to look around and fix errors as you see them.
- Add a product to yor database.
- View your product
- If this worked, congrats! You just setup a database and connected it to your application.