Werte aus der Form werden nicht an dbcontext.customers.add (NewCustomer) übergeben;C#

Ein Treffpunkt für C#-Programmierer
Anonymous
 Werte aus der Form werden nicht an dbcontext.customers.add (NewCustomer) übergeben;

Post by Anonymous »

Wenn ich das folgende Formular in den Seiten/addCustomer.Razor ausfülle, werden die Werte gelöscht, wenn ich auf "Speichern" klicke, und die obigen Fehlermeldungen werden von Customer angezeigt. /> Die Datenbanktabelle und Spalten, mit denen ich arbeite, ist: < /p>

Code: Select all

SELECT
[CustomerId],
[Name],
[Email],
[Phone],
[Address]
FROM
[Test].[dbo].[Customers]
In der Blazor -App habe ich eine Modellklasse namens Customer mit dem folgenden Code erstellt:

Code: Select all

// Models/Customer.cs
using System.ComponentModel.DataAnnotations;

namespace BlazorApp2.Models // Replace with your actual namespace
{
public class Customer
{
[Key]
public int CustomerId { get; set; }

[Required(ErrorMessage = "Name is required.")]
public string Name { get; set; }

[EmailAddress(ErrorMessage = "Invalid email address.")]
public string Email { get; set; }

[Required(ErrorMessage = "Phone number is required.")]
public string Phone { get; set; }

[Required(ErrorMessage = "Address is required.")]
public string Address { get; set; }
}
}
< /code>
Ich habe versucht, einen Haltepunkt zu < /p>
hinzuzufügendbContext.Customers.Add(newCustomer)
< /code>
, aber es scheint nicht so weit zu erreichen.  Ich habe mich gefragt, ob es mit dem oninitialisierten 
zu tun hat.

Code: Select all

@page "/customers/add"
@using BlazorApp2.Data
@using BlazorApp2.Models
@inject AppDbContext dbContext
@inject NavigationManager NavigationManager

Add New Customer

Add New Customer





Name



Email



Phone



Address



Save
[url=/customers]Cancel[/url]



@code {
private Customer newCustomer = new Customer();

protected override void OnInitialized()
{
// Display initial values when the component is initialized
Console.WriteLine("Initial values of newCustomer:");
Console.WriteLine($"  Name: {newCustomer.Name}");
Console.WriteLine($"  Email: {newCustomer.Email}");
Console.WriteLine($"  Phone: {newCustomer.Phone}");
Console.WriteLine($"  Address: {newCustomer.Address}");
}

private async Task HandleValidSubmit()
{
Console.WriteLine("Values of newCustomer before saving:");
Console.WriteLine($"  Name: {newCustomer.Name}");
Console.WriteLine($"  Email: {newCustomer.Email}");
Console.WriteLine($"  Phone: {newCustomer.Phone}");
Console.WriteLine($"  Address: {newCustomer.Address}");

dbContext.Customers.Add(newCustomer);
await dbContext.SaveChangesAsync();
NavigationManager.NavigateTo("/customers");

Console.WriteLine("Values of newCustomer after saving (should be default again):");
Console.WriteLine($"  Name: {newCustomer.Name}");
Console.WriteLine($"  Email: {newCustomer.Email}");
Console.WriteLine($"  Phone: {newCustomer.Phone}");
Console.WriteLine($"   Address: {newCustomer.Address}");
}
}
< /code>
Program.cs
using BlazorApp2.Components;
using BlazorApp2.Components.Account;
using BlazorApp2.Data;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.
builder.Services.AddRazorComponents()
.AddInteractiveServerComponents();

builder.Services.AddCascadingAuthenticationState();
builder.Services.AddScoped();
builder.Services.AddScoped();
builder.Services.AddScoped();

builder.Services.AddAuthentication(options =>
{
options.DefaultScheme = IdentityConstants.ApplicationScheme;
options.DefaultSignInScheme = IdentityConstants.ExternalScheme;
})
.AddIdentityCookies();

builder.Services.AddDbContext(options =>
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

var connectionString = builder.Configuration.GetConnectionString("DefaultConnection") ?? throw new InvalidOperationException("Connection string 'DefaultConnection' not found.");
builder.Services.AddDbContext(options =>
options.UseSqlServer(connectionString));
builder.Services.AddDatabaseDeveloperPageExceptionFilter();

builder.Services.AddIdentityCore(options => options.SignIn.RequireConfirmedAccount = true)
.AddEntityFrameworkStores()
.AddSignInManager()
.AddDefaultTokenProviders();

builder.Services.AddSingleton();

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseMigrationsEndPoint();
}
else
{
app.UseExceptionHandler("/Error", createScopeForErrors: true);
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}

app.UseHttpsRedirection();

app.UseAntiforgery();

app.MapStaticAssets();
app.MapRazorComponents()
.AddInteractiveServerRenderMode();

// Add additional endpoints required by the Identity /Account Razor components.
app.MapAdditionalIdentityEndpoints();

app.Run();

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post