Let’s suppose that you have 2 identical tables and you scaffold from the context the tables. It will give you 2 classes – with the same properties. How can you make to work for the programmer as the same class,without modifying the models scaffolded by EF ?
Example – class Ecb and class Nbr from below are the same
public partial class Ecb
     {
         public string ExchangeFrom { get; set; }
         public string ExchangeTo { get; set; }
         public DateTime Date { get; set; }
         public decimal ExchangeValue { get; set; }
     }
public partial class Nbr
    {
        public string ExchangeFrom { get; set; }
        public string ExchangeTo { get; set; }
        public DateTime Date { get; set; }
        public decimal ExchangeValue { get; set; }
    }
public partial class InfoValutarContext : DbContext
    {
        
       public InfoValutarContext(DbContextOptions<InfoValutarContext> options)
            : base(options)
        {
        }
       public virtual DbSet<Ecb> Ecb { get; set; }
        public virtual DbSet<Nbr> Nbr { get; set; }
}
Answer:
Create an interface,add partials for the classes,add partial for context ( attention to namespaces)
public interface IExchangeRate
     {
         DateTime Date { get; set; }
         string ExchangeFrom { get; set; }
         string ExchangeTo { get; set; }
         decimal ExchangeValue { get; set; }
     }
public partial class Ecb: IExchangeRate
     {
     }
     public partial class Nbr : IExchangeRate
     {
     }
public partial class InfoValutarContext
     {
         public IQueryable<IExchangeRate> RateQ(string bank)
         {
             switch (bank?.ToLower())
             {
                 case “ecb”:
                     return this.Ecb.AsNoTracking();
                 case “bnr”:
                     return this.Nbr.AsNoTracking();
                 default:
                     throw new ArgumentException($”cannot find bank {bank}”);
             }
         }
     }
Leave a Reply