0

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.

This is table tboClienti

And this is tboTecnici

Any suggestions how to fix this. Thanks in advance!

3
  • You don't have primary key defined for your entity. Do you use code first approach? Commented Jun 16, 2020 at 18:57
  • I have primary key. I just update my question with photo of my tables i.sstatic.net/kK2WD.png Commented Jun 16, 2020 at 18:59
  • Yeah, but EF doesn't know which property is your primary key. You need to specify it Commented Jun 16, 2020 at 18:59

4 Answers 4

1

As the exception text says you have to define a primary key or explicitly say that this table has no primary key.

I suggest you to make a key like

[Key]
public int Id { get; set; }

or with a Guid instead of the integer - that has the advantage that Guids can be generated before saving but it is less readable than a number - as you want.

[Key]
public Guid Id { get; set; }
Sign up to request clarification or add additional context in comments.

2 Comments

[Key] public Guid Id {get;set;} I should add it only in Model Tecnici? Because when i insert it in Model Clienti it gaves me the same error.
You have to add the Id field to the actual DB table, as well as the model that represents it. Make sure the types match (e.g. "Guid" in the model, "uniqueidentifier" in a SQL Server DB, if that's what you're using).
1

Try defining a primary key in your client class.

[Key]
public int Id { get; set; }

2 Comments

But my Id is primary key auto increment. I don't want that the user insert ID
User does not have influence on the ID property, just use the ID prop as a hidden field in your view.
1

You should specify that the column Id is your primary key, and also specify that is auto incremented by the SQL server

[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }

That way once you save your entity to the database, the Id will be automatically populated with the new generated value

Comments

0

If you face this Error and the [Key] Attribute didn't solve the issue.

You can try including the column order feature. This solves EntityType of No Key Defining Errors.

[Key]
[Column(Order = 1)]
public int Id { get; set; } 

Include System.ComponentModel.DataAnnotations namespace in your Model Class.

The key needs to be property and public.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.