Passing ViewModel to View:
In the controller:
csharp
CopyEdit
public IActionResult ProductDetails(int id)
{
var product = _context.Products
.Where(p => [Link] == id)
.FirstOrDefault();
var viewModel = new ProductViewModel
{
Id = [Link],
Name = [Link],
Category = [Link],
Price = [Link],
Discount = "10%" // Example of adding extra data
};
return View(viewModel);
}
In the view:
csharp
CopyEdit
@model ProductViewModel
<h1>@[Link]</h1>
<p>@[Link]</p>
<p>@[Link]</p>
Adding Data Annotations in [Link] Core MVC
What are Data Annotations?
Data Annotations are a set of attributes in [Link] 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.
[Link]
CopyEdit
[Range(1, 100)]
[Link] int Quantity { get; set; }
12.
[Link]:
◦ Validates that the input follows the email format.
[Link]
CopyEdit
[EmailAddress]
[Link] string Email { get; set; }
16.
[Link]:
fi
fi
◦ Validates input using a regular expression.
[Link]
CopyEdit
[RegularExpression(@"^[A-Z]+[a-zA-Z'\-'\s]*$")]
[Link] string Name { get; set; }
20.
[Link]:
◦ Used to compare two properties (e.g., password con rmation).
[Link]
CopyEdit
[Compare("Password")]
[Link] string ConfirmPassword { get; set; }
24.
[Link] for Dates:
◦ You can also apply ranges for date-time properties.
[Link]
CopyEdit
[Range(typeof(DateTime), "01/01/2021", "12/31/2025")]
[Link] DateTime StartDate { get; set; }
28.
Using Data Annotations for Validation in Forms:
• Controller Action:
csharp
CopyEdit
public IActionResult CreateProduct(Product model)
• {
• if ([Link])
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 [Link] Core MVC application.
fi
fi
Database Connection & DbContext in [Link] 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 [Link];
using [Link];
namespace [Link]
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 [Link]
2. dotnet add package [Link]
3.
4. Con gure DbContext in [Link] (Startup):
In the [Link] le, con gure the DbContext to connect to your database using a
connection string.
Example:
csharp
CopyEdit
var builder = [Link](args);
fi
fi
fi
fi
fi
5.
6. // Add DbContext to the DI container
7. [Link]<AppDbContext>(options =>
8. {
9. var connectionString =
[Link]("DefaultConnec
tion");
10. [Link](connectionString,
[Link](connectionString));
11. });
12.
13. var app = [Link]();
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 [Link] 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
[Link] le and passed to the DbContext in [Link].
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.[Link](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.[Link](id);
}
You can also query the database using LINQ:
csharp
CopyEdit
public async Task<List<Book>> GetBooksByAuthorAsync(string
author)
{
return await _context.[Link](b => [Link] ==
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.[Link](book); // Update an existing book
await _context.SaveChangesAsync(); // Save changes
return book;
}
4. Delete: