Search code examples
c#entity-frameworkef-code-firstcode-first

Entity Framework define primary key as foreign key to another entity


I have read some answers but doesn't figure out my case ...

Let's say I have a BaseEntity class like this:

public abstract class BaseEntity<TKey> : IEntity<TKey>
{
    /// <summary>
    /// Gets or sets the key for all the entities
    /// </summary>
    [Key]
    public TKey Id { get; set; }
}

And all my entities derive from this:

public class A : BaseEntity<Guid> {
    // ...props
} 

So, when I try to create an entity, to have its primary key as another entity, I get an error

EntityType 'X' has no key defined. Define the key for this EntityType.

My code:

 public class X : BaseEntity<A> { // <-- doesn't accept it
    // ...props
} 

What am I doing wrong?

Why is this kind of relation not accepted?


Solution

  • If you want that PK also will be FK to another entity, you should do this:

    public abstract class BaseEntity<TKey> : IEntity<TKey>
    {
        //[Key] attribute is not needed, because of name convention
        public virtual TKey Id { get; set; }
    }
    
    public class X : BaseEntity<Guid>//where TKey(Guid) is PK of A class
    {
        [ForeignKey("a")]
        public override Guid Id { get; set; }
        public virtual A a { get; set; }
    }