开发者

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

开发者 https://www.devze.com 2023-01-23 02:34 出处:网络
I have a POCO class, mapping to a table that basically contain three primary keys as follow: public class ContactProjectSite

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 DbCon开发者_开发知识库text 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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消