KEMBAR78
NET Reference Sheet5 | PDF | Entity Framework | Databases
0% found this document useful (0 votes)
11 views10 pages

NET Reference Sheet5

The document discusses model validation in ASP.NET Core (.NET 6 and C# 10), highlighting improvements such as better dependency injection, enhanced validation attributes, and automatic model binding. It also covers using Dapper for lightweight data access in Minimal API projects and contrasts it with Entity Framework Core, emphasizing their respective advantages and use cases. Additionally, it introduces NuGet as a package manager for .NET, facilitating library management and updates.

Uploaded by

jeevanshugoel100
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views10 pages

NET Reference Sheet5

The document discusses model validation in ASP.NET Core (.NET 6 and C# 10), highlighting improvements such as better dependency injection, enhanced validation attributes, and automatic model binding. It also covers using Dapper for lightweight data access in Minimal API projects and contrasts it with Entity Framework Core, emphasizing their respective advantages and use cases. Additionally, it introduces NuGet as a package manager for .NET, facilitating library management and updates.

Uploaded by

jeevanshugoel100
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 10

Model Validation in ASP.NET Web API (Implemented in .

NET
6 and C# 10)
With ASP.NET Core (.NET 6 and C# 10), model validation works similarly to ASP.NET Web
API 4.x, but with a few improvements and enhancements in how validation is handled.

Key Improvements in .NET 6 for Model Validation

1. Better Integration with Dependency Injection (DI): ASP.NET Core leverages DI to


automatically manage validation services and the ModelState lifecycle.

2. Enhanced Support for Validation Attributes: ASP.NET Core adds additional validation
attributes, such as [EmailAddress], [Range], and [RegularExpression],
to make validation more customizable.

3. Automatic Model Binding and Validation: ASP.NET Core automatically binds the
incoming request data to the model and triggers validation before entering the controller
action method.

1. Model Class with Validation Attributes

Just like in ASP.NET 4.x, you can use data annotations to de ne validation rules for the model.

csharp
CopyEdit
// Book.cs
using System.ComponentModel.DataAnnotations;

namespace OnlineBookStoreAPI.Models
{
public class Book
{
[Required(ErrorMessage = "Title is required")]
[StringLength(100, MinimumLength = 3, ErrorMessage =
"Title length should be between 3 and 100 characters")]
public string Title { get; set; }

[Required(ErrorMessage = "Author is required")]


public string Author { get; set; }

[Range(1, 1000, ErrorMessage = "Price must be between


1 and 1000")]
public decimal Price { get; set; }
}
}
2. Controller to Handle Model Validation
fi
ASP.NET Core automatically validates models and checks if the data is valid by the time the
controller method is called.

csharp
CopyEdit
// BookController.cs
using Microsoft.AspNetCore.Mvc;
using OnlineBookStoreAPI.Models;

namespace OnlineBookStoreAPI.Controllers
{
[Route("api/[controller]")]
[ApiController]
public class BookController : ControllerBase
{
[HttpPost]
public IActionResult AddBook([FromBody] Book book)
{
// Validate the model
if (!ModelState.IsValid)
{
return BadRequest(ModelState); // Returns
validation errors in the response
}

// If the model is valid, process the request


(e.g., add the book to the database)
return Ok("Book added successfully");
}
}
}
• Automatic Model Binding: ASP.NET Core automatically binds the incoming request data
to the Book model.

• Automatic Validation: Before executing the action method, ASP.NET Core ensures that the
data is validated using the data annotations.

• Error Handling: If the model is invalid, it returns a 400 Bad Request with the
validation errors.

3. Custom Validation

In .NET 6, you can also create custom validation attributes to perform complex validation logic
that isn’t covered by the built-in annotations.

Here’s an example of creating a custom validation attribute for checking the price:
csharp
CopyEdit
// PriceValidator.cs
using System.ComponentModel.DataAnnotations;

namespace OnlineBookStoreAPI.Validation
{
public class PriceValidator : ValidationAttribute
{
public override bool IsValid(object value)
{
if (value is decimal price && price < 1)
{
ErrorMessage = "Price must be greater than
0";
return false;
}
return true;
}
}
}
You can use this custom attribute in your model:

csharp
CopyEdit
// Book.cs
using OnlineBookStoreAPI.Validation;
using System.ComponentModel.DataAnnotations;

namespace OnlineBookStoreAPI.Models
{
public class Book
{
[Required]
public string Title { get; set; }

[Required]
public string Author { get; set; }

[PriceValidator]
public decimal Price { get; set; }
}
}
4. Fluent Validation (Optional)
For more complex scenarios, you can use FluentValidation, a popular library for .NET that
provides a more declarative way to handle model validation.

First, install the FluentValidation NuGet package:

bash
CopyEdit
dotnet add package FluentValidation
Then, create a validator class for your model:

csharp
CopyEdit
// BookValidator.cs
using FluentValidation;
using OnlineBookStoreAPI.Models;

namespace OnlineBookStoreAPI.Validators
{
public class BookValidator : AbstractValidator<Book>
{
public BookValidator()
{
RuleFor(b => b.Title)
.NotEmpty().WithMessage("Title is required")
.Length(3, 100).WithMessage("Title length
must be between 3 and 100 characters");

RuleFor(b => b.Author)


.NotEmpty().WithMessage("Author is
required");

RuleFor(b => b.Price)


.GreaterThan(0).WithMessage("Price must be
greater than 0");
}
}
}
And register the validator in the Program.cs:

csharp
CopyEdit
builder.Services.AddValidatorsFromAssemblyContaining<BookVali
dator>();
FluentValidation offers a uent API to de ne validation rules in a more readable and customizable
manner.
fl
fi
Conclusion

Model validation is an essential part of building robust, secure, and reliable Web APIs. Whether
you're working with ASP.NET 4.x or .NET 6, validation ensures that the data entering your API is
clean, consistent, and trustworthy. By using data annotations, custom validators, or
FluentValidation, you can easily enforce business rules and provide detailed error messages for
users.

Simple C# Data Access with Dapper and SQL - Minimal API Project

Introduction to Dapper

Dapper is a lightweight Object-Relational Mapping (ORM) library for .NET. It provides a simple
and fast way to interact with databases, mainly for data access operations, without the overhead
and complexity of full- edged ORM frameworks like Entity Framework (EF).

In a Minimal API project, Dapper is commonly used to perform basic CRUD operations while
maintaining a lightweight and fast execution.

Using Dapper in a Minimal API Project

Here’s an example of how to use Dapper for data access in a .NET 6 Minimal API project:

1. Install Dapper NuGet Package

First, you need to install the Dapper NuGet package.

bash
CopyEdit
dotnet add package Dapper
2. Create a Database Model

Suppose you have a simple model called Book:

csharp
CopyEdit
public class Book
{
public int Id { get; set; }
public string Title { get; set; }
public string Author { get; set; }
public decimal Price { get; set; }
}
3. Set Up Dapper with SQL Connection
fl
Create a SQLConnection and use Dapper to query the database:

csharp
CopyEdit
using Dapper;
using System.Data.SqlClient;
using Microsoft.Extensions.Configuration;

var builder = WebApplication.CreateBuilder(args);


var app = builder.Build();

// Create a route to get all books from the database


app.MapGet("/books", async (IConfiguration configuration) =>
{
string connectionString =
configuration.GetConnectionString("DefaultConnection");
using (var connection = new
SqlConnection(connectionString))
{
var books = await connection.QueryAsync<Book>("SELECT
* FROM Books");
return Results.Ok(books);
}
});

app.Run();
Advantages of Dapper in Minimal API

• Speed: Dapper is one of the fastest ORMs available due to its lightweight nature.

• Less Overhead: It doesn't require con guring models or DbContext as in Entity


Framework, making it simple to set up.

• Manual SQL Control: It gives full control over SQL queries, making it ideal for scenarios
where you need optimized, raw SQL queries.

Getting Started with Entity Framework Core

What is Entity Framework Core?

Entity Framework Core (EF Core) is a full- edged Object-Relational Mapping (ORM)
framework for .NET. It allows you to interact with databases using C# objects rather than writing
SQL queries. EF Core is lightweight, extensible, and supports multiple database engines, including
SQL Server, SQLite, MySQL, and PostgreSQL.

Setting Up EF Core in a .NET Project


fi
fl
1. Install EF Core NuGet Packages

To get started with EF Core, you need to install the required packages, typically:

bash
CopyEdit
dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools
2. Create the Model

EF Core uses POCO (Plain Old CLR Object) classes to represent database tables.

csharp
CopyEdit
public class Book
{
public int Id { get; set; }
public string Title { get; set; }
public string Author { get; set; }
public decimal Price { get; set; }
}
3. Create the DbContext

The DbContext is a central part of EF Core that allows interaction with the database.

csharp
CopyEdit
using Microsoft.EntityFrameworkCore;

public class ApplicationDbContext : DbContext


{
public DbSet<Book> Books { get; set; }

public
ApplicationDbContext(DbContextOptions<ApplicationDbContext>
options) : base(options) { }
}
4. Con gure Database Connection in Program.cs

Con gure the DbContext and connection string.

csharp
CopyEdit
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddDbContext<ApplicationDbContext>(options
=>
fi
fi
options.UseSqlServer(builder.Configuration.GetConnectionStrin
g("DefaultConnection")));

var app = builder.Build();


app.MapGet("/books", async (ApplicationDbContext context) =>
{
return await context.Books.ToListAsync();
});

app.Run();
5. Migrations and Database Creation

Once everything is set up, use EF Core’s migrations to create the database schema:

bash
CopyEdit
dotnet ef migrations add InitialCreate
dotnet ef database update

What Are Your Thoughts on Entity Framework Core vs. Dapper?

When it comes to choosing between Entity Framework Core and Dapper, both have their merits,
and the choice largely depends on your project needs.

Entity Framework Core

• Full- edged ORM: EF Core offers a complete ORM experience with automatic database
schema generation, change tracking, and lazy loading.

• Code First / Database First: It allows you to design your model rst (Code First) or
generate models from an existing database (Database First).

• Productivity: EF Core allows developers to work with C# objects directly, which can speed
up development by abstracting SQL queries.

• Learning Curve: Because it is an ORM, there’s a steeper learning curve, and it might not
be suitable for high-performance, complex queries.

Dapper

• Simplicity & Speed: Dapper is designed for high performance and simplicity. It’s very fast
for reading data, as it does not require much overhead compared to EF Core.

• Control: Dapper allows you to write raw SQL queries, giving you more control over the
database operations, which is particularly useful for highly optimized queries.

• Minimal Overhead: Unlike EF Core, Dapper doesn't need a DbContext or complex


con gurations, making it ideal for small applications or when you don’t need complex ORM
features.
fi
fl
fi
When to Use EF Core vs. Dapper

• EF Core is ideal when you need a full-featured ORM with automatic change tracking,
migrations, and relationships between tables.

• Dapper is best when you need high performance for querying large datasets and when you
want ne-grained control over the SQL queries executed.

What is NuGet?

NuGet is the of cial package manager for .NET. It enables developers to easily share and
integrate libraries or tools with .NET projects. You can use NuGet to install third-party packages,
manage dependencies, and update packages in your project.

Basic Usage of NuGet

1. Install a Package

To install a package, you can either use the NuGet Package Manager in Visual Studio or the
dotnet CLI. For example, to install Dapper:

bash
CopyEdit
dotnet add package Dapper
2. Restore Packages

NuGet will automatically restore any missing packages speci ed in the project’s .csproj le
when you build the project.

bash
CopyEdit
dotnet restore
3. Update Packages

To update a package to its latest version:

bash
CopyEdit
dotnet add package <PackageName> --version <VersionNumber>

Conclusion

• Dapper offers a lightweight, high-performance solution for simple data access scenarios
where you want full control over SQL queries.

• Entity Framework Core provides a powerful ORM for applications that require complex
data models, relationships, and automated database operations.

• NuGet is an essential tool in the .NET ecosystem for managing external libraries,
dependencies, and tools, making it easier to manage and update your project.
fi
fi
fi
fi

You might also like