Friday, 1 August 2025

Database integration with API in a .NET MAUI app.

 We'll build a small MAUI app that:

  1. Connects to a remote REST API

  2. API connects to a database (e.g., SQL Server)

  3. MAUI app fetches and displays data via HTTPClient

  4. Optionally, use local SQLite cache


Project Structure Overview

Components:

  1. Backend API (.NET 8 Web API)

  2. Database (SQL Server)

  3. MAUI App (frontend)


Part 1: Build the .NET Web API (with EF Core + SQL Server)

Step 1: Create the API Project

dotnet new webapi -n ProductApi cd ProductApi

Step 2: Define a Model

Models/Product.cs

public class Product { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } }

 Step 3: Add DbContext

Install EF Core:


dotnet add package Microsoft.EntityFrameworkCore.SqlServer dotnet add package Microsoft.EntityFrameworkCore.Tools

Data/AppDbContext.cs

using Microsoft.EntityFrameworkCore; public class AppDbContext : DbContext { public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { } public DbSet<Product> Products => Set<Product>(); }

Step 4: Register DbContext

Program.cs

builder.Services.AddDbContext<AppDbContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("Default"))); builder.Services.AddEndpointsApiExplorer(); builder.Services.AddSwaggerGen();

appsettings.json

"ConnectionStrings": { "Default": "Server=.;Database=ProductDb;Trusted_Connection=True;" }

 Step 5: Create Controller

Controllers/ProductsController.cs

[ApiController] [Route("api/[controller]")] public class ProductsController : ControllerBase { private readonly AppDbContext _context; public ProductsController(AppDbContext context) => _context = context; [HttpGet] public async Task<IEnumerable<Product>> Get() => await _context.Products.ToListAsync(); [HttpPost] public async Task<IActionResult> Post(Product product) { _context.Products.Add(product); await _context.SaveChangesAsync(); return CreatedAtAction(nameof(Get), new { id = product.Id }, product); } }

Step 6: Apply Migrations


dotnet ef migrations add InitialCreate dotnet ef database update

Run the API and check: https://localhost:port/api/products

Part 2: Connect MAUI App to the API

Step 1: Create MAUI App

dotnet new maui -n MauiWithApi cd MauiWithApi

 Step 2: Create Model

public class Product { public int Id { get; set; } public string Name { get; set; } public decimal Price { get; set; } }

Step 3: Create API Service

Services/ProductService.cs

using System.Net.Http.Json; public class ProductService { private readonly HttpClient _http; public ProductService(HttpClient httpClient) { _http = httpClient; _http.BaseAddress = new Uri("https://localhost:5001"); // replace with your API } public async Task<List<Product>> GetProductsAsync() { return await _http.GetFromJsonAsync<List<Product>>("/api/products"); } public async Task AddProductAsync(Product product) { await _http.PostAsJsonAsync("/api/products", product); } }

Step 4: Register Service

MauiProgram.cs

builder.Services.AddSingleton<HttpClient>(); builder.Services.AddSingleton<ProductService>();

 Step 5: Call Service in UI

MainPage.xaml.cs

public partial class MainPage : ContentPage { private readonly ProductService _productService; public MainPage(ProductService productService) { InitializeComponent(); _productService = productService; LoadProducts(); } private async void LoadProducts() { var products = await _productService.GetProductsAsync(); ProductsListView.ItemsSource = products; } }

MainPage.xaml


<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui" x:Class="MauiWithApi.MainPage"> <VerticalStackLayout Padding="20"> <ListView x:Name="ProductsListView"> <ListView.ItemTemplate> <DataTemplate> <TextCell Text="{Binding Name}" Detail="{Binding Price}" /> </DataTemplate> </ListView.ItemTemplate> </ListView> </VerticalStackLayout> </ContentPage>

Optional: Add SQLite Caching in MAUI

To work offline or cache data:

  1. Install SQLite NuGet:

dotnet add package sqlite-net-pcl
  1. Create local DB service (I can guide you if needed).

Now your MAUI app is:

  • Consuming a .NET Web API

  • API is connected to SQL Server using EF Core

  • You're able to fetch/post product data from mobile/desktop

No comments:

Post a Comment

Cricket Streaming MAUI App: Complete Solution

This document outlines a comprehensive solution for building a cricket streaming MAUI app with subscription plans, geo-restrictions, and pre...

Ads2