1

I have two Context as you see below.

public class AddressContext:DbContext{

    public AddressContext()
    {
        Name = "AddressContext";

    }
    public DbSet<address> addresses { get; set; }
}

public class NamesContext:DbContext{
    public NamesContext()
    {
        Name = "NamesContext";
    }
     public DbSet<Names> names { get; set; }
}

I also added enum for DatabaseType.

public enum DatabaseType
{
    address,
    names 
}

I would like to get Context based on DatabaseType.

I am not very familiar with the Factory or Strategy pattern in C#. I did try to write it but at the end I have to cast that context in order to use it.

What is the best way to get Context based on passing DatabaseType as parameter?

Nate Barbettini
  • 51,256
  • 26
  • 134
  • 147
dev
  • 898
  • 1
  • 13
  • 33
  • 1
    Factory pattern is used when all the concrete instances of different types have the same interface but implemented differently. In this case you have 2 classes having different members so it of course requires casting later. What you want here is impossible without casting **unless** somehow you just want to use some ***common members*** via an interface. Then all the classes should implement that interface and then you don't need casting. – Hopeless Sep 17 '15 at 00:00

1 Answers1

0
public DbContext GetContext(DatabaseType dbType)
{
    switch(dbType)
    {
        case DatabaseType.address:
            return new AddressContext();
        case DatabaseType.names:
            return new NamesContext();
        default:
            throw new ArgumentException("Unexpected db type.");
    }
}
Mark Seemann
  • 225,310
  • 48
  • 427
  • 736