1
votes

Using Entity Framework: Code First, I am trying to define an collection navigation property using a navigation property of a base class.

Object structure:

public class Content
{
    public int ID { get; set; }
    public ModerationStatuses ModerationStatus { get; set; }
    public ContentItemTypes ContentType { get; set; }
    public virtual User Author { get; set; }
}

public class Image : Content
{
    public Image()
        : base()
    {
        ContentType = ContentItemTypes.Image;
    }
    public string FileName { get; set; }
    public string Location { get; set; }
    public int DisplayOrder { get; set; }
    public long FileSize { get; set; }
}

public class User
{
    public int UserID { get; set; }
    public string Username { get; set; }

    public virtual ICollection<Image> Images { get; set; }
}

Context OnModelCreating:

modelBuilder.Entity<Content>()
    .Map(i => i.ToTable("Content"));

modelBuilder.Entity<Image>()
    .Map(i => i.ToTable("Images"));

When the database is generated, it creates a User_UserID foreign key constraint into the Images table instead of using Author_UserID in the Content table.

How can I get it to recognize Content..Author_UserID field as the foreign key for the ICollection<Image> navigation property?

2

2 Answers

1
votes

It's not possible. You either need to move the Author property from the Content into the Image class or make the collection in User of type ICollection<Content> Contents. A navigation property must always be declared in the entity class the inverse navigation property is refering to. It cannot be inherited from a base entity.

0
votes

Actually it is possible... You just need to add a navigation property to your Content class so that you then have a reference to map to.

Here's the thorough walkthrough.