Passing ViewModel to View:
In the controller:
csharp
CopyEdit
public IActionResult ProductDetails(int id)
{
var product = _context.Products
.Where(p => p.Id == id)
.FirstOrDefault();
var viewModel = new ProductViewModel
{
Id = product.Id,
Name = product.Name,
Category = product.Category,
Price = product.Price,
Discount = "10%" // Example of adding extra data
};
return View(viewModel);
}
In the view:
csharp
CopyEdit
@model ProductViewModel
<h1>@Model.Name</h1>
<p>@Model.Price</p>
<p>@Model.Discount</p>
Adding Data Annotations in ASP.NET Core MVC
What are Data Annotations?
Data Annotations are a set of attributes in System.ComponentModel.DataAnnotations that you
can apply to your model properties to enforce validation rules, formatting, and display attributes.
Common Data Annotations:
1. Required:
◦ Ensures that a eld is not left empty.
2. csharp
CopyEdit
fi
[Required]
3. public string Name { get; set; }
4.
5. StringLength:
◦ Speci es the maximum length of a string.
6. csharp
CopyEdit
[StringLength(100)]
7. public string Name { get; set; }
8.
9. Range:
◦ De nes a range of valid values for a numeric or date property.
10.csharp
CopyEdit
[Range(1, 100)]
11.public int Quantity { get; set; }
12.
13.EmailAddress:
◦ Validates that the input follows the email format.
14.csharp
CopyEdit
[EmailAddress]
15.public string Email { get; set; }
16.
17.RegularExpression:
fi
fi
◦ Validates input using a regular expression.
18.csharp
CopyEdit
[RegularExpression(@"^[A-Z]+[a-zA-Z'\-'\s]*$")]
19.public string Name { get; set; }
20.
21.Compare:
◦ Used to compare two properties (e.g., password con rmation).
22.csharp
CopyEdit
[Compare("Password")]
23.public string ConfirmPassword { get; set; }
24.
25.Range for Dates:
◦ You can also apply ranges for date-time properties.
26.csharp
CopyEdit
[Range(typeof(DateTime), "01/01/2021", "12/31/2025")]
27.public DateTime StartDate { get; set; }
28.
Using Data Annotations for Validation in Forms:
• Controller Action:
csharp
CopyEdit
public IActionResult CreateProduct(Product model)
• {
• if (ModelState.IsValid)
fi
• {
• _context.Add(model);
• _context.SaveChanges();
• return RedirectToAction("Index");
• }
• return View(model);
• }
•
• In the View: You don’t need to write validation code manually if you’re using Razor
Views. It automatically binds data annotations to the input elds.
html
CopyEdit
<div class="form-group">
• <label asp-for="Name"></label>
• <input asp-for="Name" class="form-control" />
• <span asp-validation-for="Name" class="text-
danger"></span>
• </div>
•
Conclusion
• Models represent the data structure of your application, holding business logic and
validations.
• ViewModels are used to tailor data speci cally for views, combining multiple models if
necessary.
• Data Annotations provide a way to enforce validation and data formatting rules in a
declarative manner.
By following these practices, you ensure better structure, separation of concerns, and
maintainability in your ASP.NET Core MVC application.
fi
fi
Database Connection & DbContext in ASP.NET Core
What is DbContext?
DbContext is a core part of Entity Framework Core (EF Core), an Object-Relational Mapper
(ORM) that enables .NET developers to interact with relational databases. DbContext serves as
the bridge between your C# application and the database. It helps manage the database connection,
query execution, and handling of database objects (tables, rows, etc.).
Key Responsibilities of DbContext:
1. Connection to the Database:
◦ It holds the database connection and is used to query and save data in the database.
2. Tracking Changes:
◦ DbContext tracks changes to entities (models) in memory and saves the changes
to the database when SaveChanges() is called.
3. Querying the Database:
◦ It provides methods like Find(), Add(), Remove(), and LINQ queries for
querying and manipulating the data.
4. Mapping Models to Tables:
◦ It maps models (C# classes) to database tables. Each DbSet<TEntity> in the
DbContext represents a table in the database.
Creating and Con guring DbContext
1. Creating a DbContext Class
To create a DbContext, follow these steps:
• Create a new class that inherits from DbContext.
• De ne DbSet<TEntity> properties for each model you want to map to a table.
Example:
csharp
CopyEdit
using Microsoft.EntityFrameworkCore;
using OnlineBookStoreAPI.Models;
namespace OnlineBookStoreAPI.Data
fi
fi
{
public class AppDbContext : DbContext
{
// Constructor to pass the DbContext options
public AppDbContext(DbContextOptions<AppDbContext>
options) : base(options)
{
}
// DbSet property for each model that maps to a
database table
public DbSet<Book> Books { get; set; }
public DbSet<Customer> Customers { get; set; }
}
}
In this example, AppDbContext is the custom DbContext class with two DbSet properties:
Books and Customers, each representing a table in the database.
Con guring DbContext in Startup
To con gure DbContext and establish a connection to your database, you need to do the
following:
1. Install EF Core NuGet Packages:
In your NuGet Package Manager or via the CLI, install the required packages for
EF Core, including the database provider (e.g., for MySQL):
bash
CopyEdit
dotnet add package Microsoft.EntityFrameworkCore
2. dotnet add package Microsoft.EntityFrameworkCore.MySql
3.
4. Con gure DbContext in Program.cs (Startup):
In the Program.cs le, con gure the DbContext to connect to your database using a
connection string.
Example:
csharp
CopyEdit
var builder = WebApplication.CreateBuilder(args);
fi
fi
fi
fi
fi
5.
6. // Add DbContext to the DI container
7. builder.Services.AddDbContext<AppDbContext>(options =>
8. {
9. var connectionString =
builder.Configuration.GetConnectionString("DefaultConnec
tion");
10. options.UseMySql(connectionString,
ServerVersion.AutoDetect(connectionString));
11. });
12.
13. var app = builder.Build();
14.
Here, the AddDbContext method registers the DbContext with dependency injection
and con gures it to connect to a MySQL database using a connection string from the app
settings.
Database Connection Con guration
1. Connection String
The connection string is typically stored in the appsettings.json le and should be added
as follows:
json
CopyEdit
{
"ConnectionStrings": {
"DefaultConnection":
"server=localhost;database=bookstore;user=root;password=yourp
assword"
}
}
Make sure to replace the values with actual credentials for your database.
2. Using Connection String in DbContext:
In the above example, the connection string DefaultConnection is retrieved from the
appsettings.json le and passed to the DbContext in Program.cs.
Working with DbContext: Performing CRUD Operations
Once DbContext is con gured, you can perform various CRUD operations (Create, Read,
Update, Delete) on your models using DbSet<TEntity> properties.
fi
fi
fi
fi
fi
1. Create (Insert):
To insert new records into the database, use the Add or AddAsync method:
csharp
CopyEdit
public async Task<Book> AddBookAsync(Book book)
{
_context.Books.Add(book); // Add a new book
await _context.SaveChangesAsync(); // Save changes to the
database
return book;
}
2. Read (Retrieve):
To retrieve data from the database, use methods like Find, FirstOrDefault, or LINQ
queries.
csharp
CopyEdit
public async Task<Book> GetBookByIdAsync(int id)
{
return await _context.Books.FindAsync(id);
}
You can also query the database using LINQ:
csharp
CopyEdit
public async Task<List<Book>> GetBooksByAuthorAsync(string
author)
{
return await _context.Books.Where(b => b.Author ==
author).ToListAsync();
}
3. Update:
To update existing records, fetch the entity, modify its properties, and then save the changes.
csharp
CopyEdit
public async Task<Book> UpdateBookAsync(Book book)
{
_context.Books.Update(book); // Update an existing book
await _context.SaveChangesAsync(); // Save changes
return book;
}
4. Delete: