EntityType 'ApplicantPosition' has no key defined

ぃ、小莉子 提交于 2019-12-01 06:02:52

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

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);

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; }
}

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!