public void ConfigureServices(IServiceCollection services)
{
services.AddMvc();
string conString = Configuration["ConnectionStrings:DefaultConnection"];
services.AddDbContext<DataContext>(options =>
options.UseSqlServer(conString));
}
public class DataContext : DbContext
{
public DataContext(DbContextOptions<DataContext> options) : base(options) { }
public DbSet<GuestResponse> Responses { get; set; }
}
public class HomeController : Controller
{
private DataContext context;
public HomeController(DataContext ctx) => context = ctx;
public IActionResult Index() => View();
public IActionResult Respond() => View();
[HttpPost]
public IActionResult Respond(GuestResponse response)
{
context.Responses.Add(response);
context.SaveChanges();
return RedirectToAction(nameof(Thanks),
new { Name = response.Name, WillAttend = response.WillAttend });
}
public IActionResult Thanks(GuestResponse response) => View(response);
public IActionResult ListResponses() =>
View(context.Responses.OrderByDescending(r => r.WillAttend));
}
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<Folder Include="wwwroot\" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.5" />
<DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.5">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</DotNetCliToolReference>
<PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="5.0.2" />
</ItemGroup>
</Project>