I'm trying to make application where i can manage customers. So i created database and table tecnici where I can insert all my technicians.
All CRUD operations worked until I created table clienti to insert my clients. I made controller, model and view for clienti, and when i run the application it gives me this error System.InvalidOperationException: 'The entity type 'Cliente' requires a primary key to be defined. If you intended to use a keyless entity type call 'HasNoKey()'.'
Error in ClientiController and it gaves me the same error when I try to load all clients ftom table clienti errore in TecniciController
This is code for ClientiController
public class ClientiController: Controller
{
private readonly AppDbContext _db;
public ClientiController(AppDbContext db)
{
_db = db;
}
public IActionResult Index()
{
var datiClienti = _db.tboClienti.ToList();
return View(datiClienti);
}
public IActionResult CreareCliente()
{
return View();
}
[HttpPost]
public async Task<IActionResult> CreareCliente(Cliente cliente)
{
if (ModelState.IsValid)
{
_db.Add(cliente);
await _db.SaveChangesAsync();
return RedirectToAction("Index");
}
return View(cliente);
}
}
This is model Cliente
public class Cliente
{
[Required(ErrorMessage = "Inserisci il nome di proprietario della azienda")]
[Display(Name = "Nome")]
public string Nome { get; set; }
[Required(ErrorMessage = "Inserisci il cognome di proprietario della azienda")]
[Display(Name = "Cognome")]
public string Cognome { get; set; }
[Display(Name = "Azienda")]
public string Nome_azienda { get; set; }
[Required(ErrorMessage = "Inserisci numero cellulare della Azienda")]
[DataType(DataType.PhoneNumber)]
[Display(Name = "Telefono")]
[RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$",
ErrorMessage = "Numero non valido")]
public string Cellulare { get; set; }
}
I have my connectionstring into appsettings.json
And this is the calass where I configure db:
public class AppDbContext: DbContext
{
public AppDbContext(DbContextOptions<AppDbContext> options): base (options)
{
}
public DbSet<Tecnico> tboTecnici { get; set; }
public DbSet<Cliente> tboClienti { get; set; }
}
Until was only one table (table: tecnici) it did not make me problems. When I create controller model and view for table tboClienti it gives me the error.
Any suggestions how to fix this. Thanks in advance!