views:

307

answers:

1

I am struggling already several days to solve my problem with primary key usage. Please, someone help me to solve this puzzle!!!

I am using Entity Framework with CTP4 using Code First approach. I adopted for my project Repository pattern published by Huyrua see here. I am very exited with this patern and with CTP4 possibilities in particular.

For Entity definition we use several nesting layers. At the very bottom we have BaseEntity, that contains some general fields, like that:

public abstract class BaseEntity: IEntityBase
    {
        public virtual Nullable<System.DateTime> InsertDate { get; set; }
        public virtual Nullable<int> PK_InsertUserAccount { get; set; }
        public virtual byte[] TimeStamp { get; set; }
    }

Then we derive from this class for our concrete entities, for example:

public class Person : BaseEntity
    {
        public virtual int PK_Person { get; set; }
        public virtual byte PersType { get; set; }
        public virtual string eMail { get; set; }
        public virtual string Name { get; set; }
    }

Note! We have one key difference - DB table primary key name is NOT "Id"! We are using pattern PK_. For this reason we do not include PK field definition in the BaseEntity. Further, we use use EntityConfiguration to map our non-by-convention primary key:

public class PersonMapping : EntityConfiguration<Person>
    {
        public PersonMapping()
        {
            this.HasKey(p => p.PK_Person);
            this.Property(p => p.PK_Person).IsIdentity();
            this.MapSingleType().ToTable("dbo.Person"); //otherwise by convention it is  converted to "People"
        }
    }

And here we have problems. When I try to use Person entity, I get an error 'Unable to infer a key for entity type 'KDC.Model.Entities.BaseEntity''. Seems that ObjectContext needs to have defined primary key in the very base class. Because, when for experimental purposes I move PK field definition in the BaseEntity, everything worked fine. But this not possible in our case, because for each table we hav differnet Primary key field name.

I do not know way and where I am wrong! Please, help me!!!

+1  A: 

Instead of using MapSingleType, try using MapHierarchy and specify the fields.

For Example

modelBuilder.Entity<Person>().MapHierarchy(p => new { p.PK_Person, p.PersType, p.Name, p.eMail, p.InsertDate, p.PK_InsertUserAccount, p.TimeStamp}).ToTable("Persons");
ckal