Saxman
Saxman

Reputation: 5089

EF POCO - Unable to infer a key for entity type?

I have a POCO class, mapping to a table that basically contain three primary keys as follow:

public class ContactProjectSite
    {
        public int ContactID { get; set; }
        public int ProjectID { get; set; }
        public int SiteID { get; set; }

        public virtual Contact Contact { get; set; }
        public virtual Project Project { get; set; }
        public virtual Site Site { get; set; }
    }

Here's the class that inherit the DbContext class, override the OnModelCreating method:

public class TLI : DbContext
{
    public DbSet<ContactProjectSite> ContactsProjectSite { get; set; }
    protected override void OnModelCreating(System.Data.Entity.ModelConfiguration.ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<ContactProjectSite>().MapSingleType(cps => new
        {
            cpcid = cps.ContactID,
            cppid = cps.ProjectID,
            cpsid = cps.SiteID
        }).ToTable(new StoreTableName("contacts_ps", "dbo"));
    }
}

However, when running this, I gets this error: *Unable to infer a key for entity type 'Library.Models.ContactProjectSite'. * Any idea why?

Thanks.

Upvotes: 1

Views: 1325

Answers (1)

Ian Mercer
Ian Mercer

Reputation: 39277

You can apply the [Key] attribute to indicate which property is the primary key when EF can't figure it out from names/types. I think you can apply it multiple times to create a composite key.

Upvotes: 1

Related Questions