Search code examples
c#entity-framework-5

Bounded DbContex and Inheritance


I have a model consisting of two separate contexts, so I implement in two separate DbContext, I have a third DbContext which is the base of these two DbContextes, and I have a Base class which classes from GeographicDbContext and PublishingDbContext inherited from that class. And there is a relationship between Publisher class in PublishingDbContext and Country in GeographicDbContext. Now I want to tell the EntityFramework that I have a base abstract class which has an ID that should be mapped to each table in subclasses. I know I have to place this code in the OnModelCreating event of DbContext

modelBuilder.Entity<Country>().Map(x =>
            {
                x.MapInheritedProperties();
                x.ToTable("Country");
            }); 

since Country is a class in GeographicDbContext, I want to put this code inside that DbContext, but when using Publisher class and its navigational property Country, so I have to add this piece of code into PublishingDbContext as well because PublishingDbContext will import all related entities into the model. Is there any way to put this code only in GeographicDbContext, I don't want to add this code for every reachable entity in a particular DbContext.

public abstract class BaseEntity
{
    [Key]
    public int ID { get; set; }
}

[Table("Country")]
public class Country : BaseEntity
{
    public string Name { get; set; }
    public int Code { get; set; }
}

public class Publisher: BaseEntity
{
    public string Title { get; set; }

    [Column("CountryID")]
    public int? CountryID { get; set; }

    [ForeignKey("CountryID")]
    public Country Country { get; set; }
}

in the above code, every class is in a different assembly and in a different DbContext.


Solution

  • Knowing this is a very old question, and I'm not working on EF5 anymore, but I'm writing the solution I chose for reference.

    It's not correct to have relation between separate "DbContext"s so we need another readonly class which mimics Country class, the name can be CountryView for example, and you can map this class to the same table on GeographicDbContext, or a readonly view in your database. so you cannot edit this class from other DbContexts except the DbContext which it's this class's owner. you can only view the readonly values.