ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
3,150 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Project Description:
Three Property Sets: A, B, and C
A and B with one-to-many relationships with **C
Error: when trying to view A, Details view.
Tutorial: Add enrollments to the Details view
Environment: Net Core 6 MVC, Visual Studio Community 2022 (64 bit), WIndows 11
**Code Follows:
Context**
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using ViewModel.Models;
namespace ViewModel.Data
{
public class ViewModelContext : DbContext
{
public ViewModelContext (DbContextOptions<ViewModelContext> options)
: base(options)
{
}
public DbSet<ViewModel.Models.A> A { get; set; } = default!;
public DbSet<ViewModel.Models.B>? B { get; set; }
public DbSet<ViewModel.Models.C>? C { get; set; }
}
}
A
namespace ViewModel.Models
{
public class A
{
public int Id { get; set; }
public string? One { get; set; }
public string? Two { get; set; }
public string? Three { get; set; }
// _______________________________________
public IEnumerable<C>? C { get; set; }
}
}
B
namespace ViewModel.Models
{
public class B
{
public int Id { get; set; }
public string? One { get; set; }
public string? Two { get; set; }
public string? Three { get; set; }
// _______________________________________
public IEnumerable<C>? C { get; set; }
}
}
C
using System.Security.Cryptography.Xml;
namespace ViewModel.Models
{
public class C
{
public int Id { get; set; }
public int AId { get; set; }
public int BId { get; set; }
// _______________________________________
public A? A { get; set; }
public B? B { get; set; }
}
}
View.A
Controller, Details Action Method
// GET: A/Details/5
public async Task<IActionResult> Details(int? id)
{
if (id == null || _context.A == null)
{
return NotFound();
}
var a = await _context.A
.FirstOrDefaultAsync(m => m.Id == id);
if (a == null)
{
return NotFound();
}
return View(a);
}
Build Results
========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========
Run web app, Select A, Details view
you need to use .Include() to load navigation properties. see tutorial.