EntityType 'ApplicantPosition' has no key defined

后端 未结 4 623
隐瞒了意图╮
隐瞒了意图╮ 2021-01-13 05:36

When running my first asp.net mvc application I got this error I thought that entity framework automatically would create the keys of column names that end with Id? isnt it

相关标签:
4条回答
  • 2021-01-13 06:05

    In your case, EF naming convention first looks for an ID (case-insensitive) column. If nothing, looks for ApplicantImageId and when it founds nothing, it raises that error.

    So, you should add the [Key] attribute on your ID:

    public class ApplicantImage
    {
        [Key]
        public int ApplicantId { get; private set; }
        public byte[] Image { get; set; }
    }
    

    and if ApplicantId column is identity in your database, you should add another attribute too:

    public class ApplicantImage
    {
        [Key]
        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
        public int ApplicantId { get; private set; }
        public byte[] Image { get; set; }
    }
    
    0 讨论(0)
  • 2021-01-13 06:09

    I know this is an old question but it is still relevant. I ran into the same situation however we use a .tt file to generate the .cs from our edmx. Our .tt is setup to add the [Key] attribute on our first column of the table for most situations, but in my case i was using a row over () in SQL to generate unique id's for the first column (works great for most situations). The problem with that was it makes a nullable and the .tt wasn't setup to add [Key] in this case.

    Wrapping the row Over() in a ISNULL ((),0) was able to fix making the column not null and solved my problem. Otherwise, as mentioned by marianosz, simply using the .HasKey() in your data context will work fine too.

    0 讨论(0)
  • 2021-01-13 06:11

    EF Code First can only infer that a property is a primary key if the property is called Id or <class name>Id (or if it is annotated with the Key attribute). So you need to extend your e.g. ApplicantImage with an ApplicantImageId or Id property etc.

    Edit: An artice about the coneventions: Conventions for Code First

    0 讨论(0)
  • 2021-01-13 06:23

    You can add the [Key] atributte to the property ApplicantId or do it via Fluent API overriding OnModelCreating method DbContext

    modelBuilder.Entity<ApplicantImage >().HasKey(p => p.ApplicantId);
    
    0 讨论(0)
提交回复
热议问题