NET Reference Sheet2
NET Reference Sheet2
In the controller:
csharp
CopyEdit
public IActionResult ProductDetails(int id)
{
var product = _context.Products
.Where(p => p.Id == id)
.FirstOrDefault();
return View(viewModel);
}
In the view:
csharp
CopyEdit
@model ProductViewModel
<h1>@Model.Name</h1>
<p>@Model.Price</p>
<p>@Model.Discount</p>
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.
26.csharp
CopyEdit
• Controller Action:
csharp
CopyEdit
• {
• 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.).
2. Tracking Changes:
◦ DbContext tracks changes to entities (models) in memory and saves the changes
to the database when SaveChanges() is called.
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)
{
}
To con gure DbContext and establish a connection to your database, you need to do the
following:
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.
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.
In the above example, the connection string DefaultConnection is retrieved from the
appsettings.json le and passed to the DbContext in Program.cs.
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: