Home > Net >  cannot perform override in class inheritance in ADO .NET Entity Model edmx
cannot perform override in class inheritance in ADO .NET Entity Model edmx

Time:12-14

I have to build a .net web application accessing tables of an existing db.

The db uses different tables for different companies: customers in company "ACorp" are stored in table "ACorpCustomers", those in company "B" are stored in table "BCorpCustomers".

Using ADO .NET Entity Model, I created a different Db Context for each Company:

public partial class ACorpContext : DbContext
    {
        public ACorpContext()
            : base("name=ACorpContext")
        {
        }
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            throw new UnintentionalCodeFirstException();
        }
    
        public virtual DbSet<ACorpCustomer> ACorpCustomers { get; set; }
    }
}

The edmx generates also the class

public partial class ACorpCustomer
{
    public string Name { get; set; }
    public string Phone { get; set; }
}

I created a parent class Customer to be used in the application, with the same properties:

public class ACorpCustomer
{
    public virtual string Name { get; set; }
    public virtual string Phone { get; set; }
}

I havent't found a way to let the specific entity ACorpCustomers inherit from the parent Customer; the edmx returns the inheritance error, but there is no way to override the properties.

CodePudding user response:

Your definition

public partial class ACorpCustomer

has nothing to do with inheritance. partial is a .NET moderator that signifies that your class definition is a part of the bigger definition. For example if you have your class split between 2 code files. .Net "puts" them together and you endup with one type

Here what you seem need to do is


public abstract class Customer
{
    public string Name { get; set; }
    public string Phone { get; set; }
}

public class ACorpCustomer : Customer
{
    // may be, some unique properties here
}

public class BCorpCustomer : Customer
{
    // may be, some unique properties here
}

The properties Name and Phone don't even need to be virtual. Looking back into your title, there is nothing that you need to override. Nothing that I see..

CodePudding user response:

This is trivial in Code-First, which you can (and should) use with an existing database. Just map the single Customer entity to the correct table for each DbContext:

    public partial class ACorpContext : MyBaseDbContext
    {
    
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Customer>().ToTable("ACorpContext");
        }
    
        public virtual DbSet<Customer> Customers{ get; set; }
    }
  • Related