backend
Entity framework core:
public string Name {get; set;} = null!; //here Name is not nullable
public string? Address {get; set;} //here Address is nullable
https://www.youtube.com/playlist?list=PLdo4fOcmZ0oXCPdC3fTFA3Z79-eVH3K-s
Suppose there is a delivery website: Contoso Pizza. How they will work:
So in the database, we are going to add data of customers, when they order, we need to add order details, that will be separated order and order details, also those are the things that they have ordered we need to store those. Pretty simple right?
Customer:
int Id
string FirstName
string LastName
string Address
string Phone
string Email
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace EntityFramework.Models
{
internal class Customer
{
public int Id { get; set; }
public string FirstName { get; set; } = null!;
public string LastName { get; set; } = null!;
public string? Address { get; set; }
public string? Phone { get; set; }
public ICollection<Order> Orders { get; set; } = null!;
}
}
Here: Order is a collection of order object, orders can be multiple so we used ICollection.
then the customer places order:
Order:
int Id
timestamp OrderPlaced
timestamp OrderFulfilled
int CustomerId
namespace EntityFramework.Models
{
public class Order
{
public int Id { get; set; }
public DateTime OrderPlaced { get; set; }
public DateTime OrderFulfilled { get; set; }
public int CustomerId { get; set; } //its a foreign key to direct the customer id that we have already created.
public Customer Customer { get; set; } = null!;
public ICollection<OrderDetails> OrderDetails { get; set; } = null!;
}
}
plus, order details:
OrderDetails:
int Id
int Quantity
int OrderId
int ProductId
those are the things he ordered:Product
Product:
int Id
string Name
decimal Price
So, the EF code for product would be:
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
namespace EntityFramework.Models
{
internal class Product
{
public int Id { get; set; }
public string Name { get; set; } = null!;
[Column(TypeName = "decimal(6,2)")]
public decimal Price { get; set; }
}
}
Now we will create a DbContext class. We are just introducing our existing ef classes to the DbContext here. DbContext is just representing the session in the database.
Custom middleware: Create the asp.net core empty repo, in the program.cs file we can write our own middleware and setup accordingly.
var builder = WebApplication.CreateBuilder(args);
var app = builder.Build();
/*app.MapGet("/", () => "Hello World!");
*/
app.Use(async (context, next) =>
{
await context.Response.WriteAsync("This is a custom middleware! \n");
await next(context);
});
app.Use(async (context, next) =>
{
await context.Response.WriteAsync("This is the next middleware, its working!");
await next(context);
});
app.Run();
Comments
Post a Comment