27

I'm writing an ASP.NET Web API right now and everything works just fine for 2 controllers. Now I try to do exactly the same as before but this time I get a weird error:

System.InvalidOperationException: "The entity type 'UserItem' requires a primary key to be defined."

Well then, why does UserItem needs a primary key when the others don't?

This is my UserItem class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ModulApi.Models
{
    public class UserItem
    {
        public int matrikelnr { get; set; }
        public string studiengang { get; set; }
        public string user_semester { get; set; }
        public string user_max_klausur { get; set; }

        //Not necessary Constructor. I try to fix the primary Key error.
        public UserItem()
        {
            this.matrikelnr = 0;
            this.studiengang = "";
            this.user_max_klausur = "";
            this.user_semester = "";
        }
    }
}

And my WORKING LoginItem class:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace ModulApi.Models
{
    public class LoginItem
    {
        public long Id { get; set; }
        public string username { get; set; }
        public string password { get; set; }
        public string matrikelnr { get; set; }
        public string email { get; set; }
        public string email_verified { get; set; }

        public LoginItem()
        {
            this.Id = 0;
            this.username = "";
            this.password = "";
            this.matrikelnr = "";
            this.email = "";
            this.email_verified = "";
         }
    }
}

As you see, I got getter and setter set up, so the error can't be there.

Here is where the error occurs:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using ModulApi.Models;
using ModulApi.DBConnectors;

// For more information on enabling Web API for empty projects, visit 
https://go.microsoft.com/fwlink/?LinkID=397860

namespace ModulApi.Controllers
{
    [Route("api/user")]
    public class UserController : Controller
    {
        private readonly UserContext _context;

        public UserController(UserContext context)
        {
            _context = context;

            if (_context.UserItems.Count() == 0)  <--- Error right here
            {
                 getDataFromConnector(_context);
            }
        }

        private void getDataFromConnector(UserContext context)
        {
            //Getting my Data from Database method
        }
        .
        .

Well Since it is in a Context call, I'll attach UserContext as well, but again it is the same as in LoginContext, which works just fine.

UserContext:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;

namespace ModulApi.Models
{
    public class UserContext : DbContext
    {
        public UserContext(DbContextOptions<UserContext> options) : base(options)
        {
        }

        public DbSet<UserItem> UserItems { get; set; }
    }
}

Has anyone a clue why I get this weird error? And why all other Controllers work fine which do exactly the same?

2
  • EF sets LoginItem member Id as default primary key. Since no member Id or UserItemId is present in UserItem you get this error
    – ahrberg
    Jan 12, 2018 at 12:11
  • may be in your database table you don't set the primary key
    – user8507737
    Jan 12, 2018 at 12:21

4 Answers 4

62

Entity Framework goes by convention. That means that if you have an object with a property named Id, it will assume that it is the Primary Key for the object. That's why your LoginItemclass works fine.

Your UserItem class has no such property, and therefor it can't figure out what to use as the primary key.

To fix this, affix the KeyAttribute to whatever your primary key is on your class. For example:

// Need to add the following using as well at the top of the file:
using System.ComponentModel.DataAnnotations;

public class UserItem
{
    [Key]
    public int matrikelnr { get; set; }
    public string studiengang { get; set; }
    public string user_semester { get; set; }
    public string user_max_klausur { get; set; }

    // ...
}
7
  • 1
    Thank you, that work. But I also had to add "using System.ComponentModel.DataAnnotations"
    – Buzzet
    Jan 12, 2018 at 12:20
  • Correct. That's why I linked the attribute so you can see everything about it, including the namespace. However, I will add that to the answer as well.
    – krillgar
    Jan 12, 2018 at 12:25
  • So, that means that you cannot use EF Core to map results from SPs to DTOs, without defining a primary key for them? Isn't this a bit weird? The Full framework EF could do this mapping without problems (ctx.Database.SqlQuery<MyDTO>("dbo.MySP {0}", docId).FirstOrDefault();). Mar 28, 2019 at 10:41
  • @user2173353 I'm fairly certain you needed a PK in EF 5.0 (.NET Framework) as well. That code that you shared is running a manual query as opposed to using the DbSet properties on the Context that the question was asking about. For those queries, you can project it into any C# object that contains the properties you'll return from the Stored Procedure. You can still do that in EF Core.
    – krillgar
    Apr 30, 2019 at 15:27
  • I think in older versions of the EF, this was not a requirement.
    – Fandango68
    Feb 25, 2022 at 7:01
9

Your working LoginItem has:

public long Id { get; set; }

Properties called *id are detected and used as the primary key by convention. You need to explicitly set the [Key] attribute otherwise.

0
6

There are multiple was to resolve this.

1.Decorate matrikelnr as [Key]

public class UserItem
{
    [Key]
    public int matrikelnr { get; set; }
    public string studiengang { get; set; }
    public string user_semester { get; set; }
    public string user_max_klausur { get; set; }

    //Not necessary Constructor. I try to fix the primary Key error.
    public UserItem()
    {
        this.matrikelnr = 0;
        this.studiengang = "";
        this.user_max_klausur = "";
        this.user_semester = "";
    }
}

2.Rename matrikelnr with matrikelnrId . With *Id , EF will consider it as PK.

 public class UserItem
{
    [Key]
    public int matrikelnrId { get; set; }
    public string studiengang { get; set; }
    public string user_semester { get; set; }
    public string user_max_klausur { get; set; }

    //Not necessary Constructor. I try to fix the primary Key error.
    public UserItem()
    {
        this.matrikelnrId = 0;
        this.studiengang = "";
        this.user_max_klausur = "";
        this.user_semester = "";
    }
}
4

Beacuse you register UserItem with DBContext, DBContext Bind this user item with SQL database Table with which it is necessary to set any primary key attribute in UserItem. Try this , it will resolve your problem. [Key] public int matrikelnr { get; set; }

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.