I want to derive a class from MigrateDatabaseToLatestVersion in my project.
public abstract class BaseDatabaseInitializer<TContext> : MigrateDatabaseToLatestVersion<TContext, MigrationConfiguration>
where TContext : DbContext
MigrationConfiguration class looks like this
internal sealed class MigrationConfiguration : DbMigrationsConfiguration<QAdminDbContext>
{
public MigrationConfiguration()
{
AutomaticMigrationsEnabled = true;
}
protected override void Seed(QAdminDbContext context)
{
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data. E.g.
//
// context.People.AddOrUpdate(
// p => p.FullName,
// new Person { FullName = "Andrew Peters" },
// new Person { FullName = "Brice Lambson" },
// new Person { FullName = "Rowan Miller" }
// );
//
}
}
But I am not allowed to do so and am getting an error
"Inconsistent accessibility: base class 'System.Data.Entity.MigrateDatabaseToLatestVersion<TContext,Lutron.Application.QAdmin.Database.EntityConfiguration.MigrationConfiguration>' is less accessible than class 'Lutron.Application.QAdmin.Database.BaseDatabaseInitializer<TContext>' E:\Proj\Lutron\Code\src\Lutron\Gulliver\QAdmin\DataAccess\Database\BaseDatabaseInitializer.cs 17 27 Database"
This is due to the fact that MigrateDatabaseToLatestVerion class has explicitly defined where clause for MigrationConfigurationContext.
Since, in my custom class, I have explicitly defined 'Configuration' class, I can't add where clause.
The error occurs because the abstract initializer class is a public class, but the migrations class is internal. Change them both to public classes or both to internal classes, but then there is another issue.
The C# compiler will see that someone is allowed to try BaseDatabaseInitializer<SomeOtherContext>, but the MigrationConfiguration class isn't convertible to a migration with a type parameter of SomeOtherContext, so it won't allow the code to compile.
There are some possible solutions, but I think it depends on what you are trying to achieve. If you want more control over how and when the migrations execute I'd probably take a different approach and implement IDatabaseInitializer, which still allows you to plug the class into the application as a database initializer, something like:
public abstract class BaseDatabaseInitializer<TContext> :
IDatabaseInitializer<TContext> where TContext : DbContext
{
private readonly DbMigrationsConfiguration<TContext> _migrations;
protected BaseDatabaseInitializer(DbMigrationsConfiguration<TContext> migrations)
{
_migrations = migrations;
}
public void InitializeDatabase(TContext context)
{
new DbMigrator(_migrations).Update();
}
}
Related
I want to develop a structure that will support generic DbContexts in the .Net Core Web API project and can be used in the repository pattern. Mysql and PostreSql databases are sufficient for now. Can you help with this?
Create a new .Net Core Web API project.
Add a new folder in the project called DataAccess and create a new class called BaseDbContext that inherits from DbContext. This class will contain the common properties and methods for all your DbContexts.
public class BaseDbContext : DbContext
{
public BaseDbContext(DbContextOptions options) : base(options) { }
//...
}
Create a new class called MySqlDbContext that inherits from BaseDbContext. This class will contain the properties and methods specific to the MySQL database.
public class MySqlDbContext : BaseDbContext
{
public MySqlDbContext(DbContextOptions<MySqlDbContext> options) : base(options) { }
//...
}
Create a new class called PostgreSqlDbContext that inherits from BaseDbContext. This class will contain the properties and methods specific to the PostgreSQL database.
public class PostgreSqlDbContext : BaseDbContext
{
public PostgreSqlDbContext(DbContextOptions<PostgreSqlDbContext> options) :
base(options) { }
//...
}
Create a new folder in the project called Repositories and create a new class called BaseRepository that will contain the common methods for all your repositories.
public class BaseRepository<T> where T : class
{
protected readonly DbContext _context;
public BaseRepository(DbContext context)
{
_context = context;
}
//...
}
Create new classes for each repository that inherits from BaseRepository and pass the appropriate DbContext to the base constructor.
public class MySqlRepository : BaseRepository<MySqlDbContext>
{
public MySqlRepository(MySqlDbContext context) : base(context) { }
//...
}
and
public class PostgreSqlRepository : BaseRepository<PostgreSqlDbContext>
{
public PostgreSqlRepository(PostgreSqlDbContext context) : base(context) { }
//...
}
In your controllers you can now inject the appropriate repository and use it to interact with the database.
You can also use dependency injection to inject the appropriate DbContext based on the configuration.
Additional:
Here is an example of how you can do this:
In your appsettings.json file, add a section for the database connection information, such as:
{
"ConnectionStrings": {
"MySqlConnection": "Server=localhost;Database=mydb;User=user;Password=password;",
"PostgreSqlConnection": "Host=localhost;Database=mydb;Username=user;Password=password;"
},
"DatabaseProvider": "MySql"
}
Here the DatabaseProvider field indicate the database that user wants to use.
2. In your Startup.cs file, create a new method called ConfigureDbContext that will configure the DbContext based on the configuration in the appsettings file
public void ConfigureDbContext(IServiceCollection services)
{
var connectionString = Configuration.GetConnectionString("MySqlConnection");
var provider = Configuration.GetValue<string>("DatabaseProvider");
if(provider == "MySql")
{
services.AddDbContext<MySqlDbContext>(options => options.UseMySql(connectionString));
}
else if (provider == "PostgreSql")
{
services.AddDbContext<PostgreSqlDbContext>(options => options.UseNpgsql(connectionString));
}
}
In the ConfigureServices method in Startup.cs, call the ConfigureDbContext method to configure the DbContext.
public void ConfigureServices(IServiceCollection services)
{
ConfigureDbContext(services);
//...
}
In your controllers, you can now inject the appropriate DbContext using dependency injection.
public class MyController : Controller
{
private readonly IDbContext _context;
public MyController(IDbContext context)
{
_context = context;
}
//...
}
Single interface: IDoSomething {...}
Two classes implement that interface:
ClassA : IDoSomething {...}
ClassB : IDoSomething {...}
One class uses any of those classes.
public class DummyClass(IDoSomething doSomething) {...}
code without Autofac:
{
....
IDoSomething myProperty;
if (type == "A")
myProperty = new DummyClass (new ClassA());
else
myProperty = new DummyClass (new ClassB());
myProperty.CallSomeMethod();
....
}
Is it possible to implement something like that using Autofac?
Thanks in advance,
What you are looking for is, as I remember, the Strategy Pattern. You may have N implementations of a single interface. As long you register them all, Autofac or any other DI framework should provide them all.
One of the options would be to create a declaration of the property with private setter or only getter inside Interface then implement that property in each of the class. In the class where you need to select the correct implementation, the constructor should have the parameter IEnumerable<ICommon>.
Autofac or any other DI frameworks should inject all possible implementation. After that, you could spin foreach and search for the desired property.
It may look something like this.
public interface ICommon{
string Identifier{get;}
void commonAction();
}
public class A: ICommon{
public string Identifier { get{return "ClassA";} }
public void commonAction()
{
Console.WriteLine("ClassA");
}
}
public class A: ICommon{
public string Identifier { get{return "ClassB";} }
public void commonAction()
{
Console.WriteLine("ClassA");
}
}
public class Action{
private IEnumerable<ICommon> _common;
public Action(IEnumerable<ICommon> common){
_common = common;
}
public void SelectorMethod(){
foreach(var classes in _common){
if(classes.Identifier == "ClassA"){
classes.commonAction();
}
}
}
}
I'd like to intercept var context = new MyDbContext() to return a different constructor call instead.
The great thing about EFfort is that it let's you set up an easy in-memory database for unit testing.
var connection = Effort.DbConnectionFactory.CreateTransient();
var testContext = new MyDbContext(connection);
But then you'd have to inject that context into your repository.
public FooRepository(MyDbContext context) { _context = context; }
Is it possible to just intercept var context = new MyDbContext() , so that it returns the testContext?
using (var context = new MyDbContext()) {
// this way, my code isn't polluted with a ctor just for testing
}
You have two possible options. Using factories or via Aspect oriented programming (like PostSharp)
referencing this article: http://www.progware.org/Blog/post/Interception-and-Interceptors-in-C-(Aspect-oriented-programming).aspx
Using PostSharp (AOP)
PostSharp is a great tool and can achieve the most clean interception
possible (meaning no changes in your classes and object generation at
all even if you do not your factories for object creation and/or
interfaces) but it is not a free library. Rather than creating proxies
at runtime, it injects code at compile time and therefore changes your
initial program in a seamless way to add method interception.
.....
The cool thing in this is that you do not change anything else in your
code, so your object can be still generated using the new keyword.
Using DI and Factory-pattern
I personally prefer the factory-pattern approach, but you seem apposed to having to inject any dependencies into your classes.
public interface IDbContextFactory<T> where T : DbContext {
T Create();
}
public class TestDbContextFactory : IDbContextFactory<MyDbContext> {
public MyDbContext Create() {
var connection = Effort.DbConnectionFactory.CreateTransient();
var testContext = new MyDbContext(connection);
return testContext;
}
}
public class FooRepository {
MyDbContext _context;
public FooRepository(IDbContextFactory<MyDbContext> factory) {
_context = factory.Create();
}
}
(edit: I just realized this isn't actually returning the other ctor call. working on it.)
Figured it out. Simple enough if you know how to do it:
[TestMethod]
public void Should_have_a_name_like_this()
{
// Arrange
var connection = Effort.DbConnectionFactory.CreateTransient();
ShimSolrDbContext.Constructor = context => new SolrDbContext(connection);
// Act
// Assert
}
And as usual, EFfort requires this constructor in the DbContext class:
public class SomeDbContext
{
public SomeDbContext() : base("name=Prod")
{
}
// EFfort unit testing ctor
public SomeDbContext(DbConnection connection) : base(connection, contextOwnsConnection: true) {
Database.SetInitializer<SolrDbContext>(null);
}
}
But it means the repo is blissfully unaware of the special Transient connection:
public class SomeRepository
{
public void SomeMethodName()
{
using (var context = new SomeDbContext())
{
// self-contained in repository, no special params
// and still calls the special test constructor
}
}
}
EF has generated for me some partial classes, each with a constructor, but it says not to touch them (example below), now if I make my own secondary partial class and I want to have a constructor that automatically sets some of the fields how do I do so as it would conflict?
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Breakdown.Models
{
using System;
using System.Collections.Generic;
public partial class Call
{
public Call()
{
this.Logs = new HashSet<Log>();
}
...
}
}
Partial methods can help you here, in the T4 Templates define a body-less partial method and call that inside the constructor.
public <#=code.Escape(entity)#>()
{
...
OnInit();
}
partial void OnInit();
Then in your partial class define the partial method and place inside that what you want to do in the constructor. If you don't want to do anything then you don't need to define the partial method.
partial class Entity()
{
partial void OnInit()
{
//constructor stuff
...
}
}
http://msdn.microsoft.com/en-us/library/vstudio/6b0scde8.aspx
This is not possible.
Partial classes are essentially parts of the same class.
No method can be defined twice or overridden (same rule apply for the constructor also)
But You can use below mentioned Workaround :
//From file SomeClass.cs - generated by the tool
public partial class SomeClass
{
// ...
}
// From file SomeClass.cs - created by me
public partial class SomeClass
{
// My new constructor - construct from SomeOtherType
// Call the default ctor so important initialization can be done
public SomeClass(SomeOtherType value) : this()
{
}
}
for more information check Partial Classes, Default Constructors
I hope this will help to you.
I wanted to do the same recently and ended up modifying the T4 template so I could implement my own parameterless constructor manually. To accomplish this you can remove the constructor from the generated classes and move the instantiation of collections etc to outside the constructor so this:
public Call()
{
this.Logs = new HashSet<Log>();
}
becomes this:
private ICollection<Log> logs = new HashSet<Log>();
public virtual ICollection<Log> Logs
{
get { return this.logs; }
set { this.logs = value; }
}
The drawback I suppose is that the generated classes are not as "clean". That is you can't just have auto-implemented properties for your complex/nav types.
In your model.tt file you can prevent the constructor generation by removing the below code, commenting it out or by just putting in a false into the conditional so it never gets executed:
if (propertiesWithDefaultValues.Any() || complexProperties.Any())
{
#>
public <#=code.Escape(complex)#>()
{
<#
foreach (var edmProperty in propertiesWithDefaultValues)
{
#>
this.<#=code.Escape(edmProperty)#> =
<#=typeMapper.CreateLiteral(edmProperty.DefaultValue)#>;
<#
}
foreach (var complexProperty in complexProperties)
{
#>
this.<#=code.Escape(complexProperty)#> = new
<#=typeMapper.GetTypeName(complexProperty.TypeUsage)#>();
<#
}
#>
}
Then below this you need to do some modification where properties are generated for your complex and navigation types. Add a private var with object instantiation and a property for accessing the private var for each of these eg:
if (complexProperties.Any())
{
foreach(var complexProperty in complexProperties)
{
//generate private var + any instantiation
//generate property for accessing var
}
}
Depending on the complexity of your model there may be other areas you need to modify. Hopefully this gets you started.
If I well understand the question, you need this constructor when creating a new entity, that is an entity that was not persisted before.
My case was to set a default value to all datetime, that is initalize them to "the begining of time" : 1900-01-01.
In this case I use an entity factory
public static T GetNewEntity<T> () {
T e;
try {
e = Activator.CreateInstance<T>();
} catch {
e = default(T);
}
SetDefaults(e);
return e;
}
Each time I need a new Entity I use
Entity e = GetNewEntity<Entity>();
with SetDefaults as :
public static void SetDefaults (object o) {
Type T = o.GetType();
foreach ( MemberInfo m in T.GetProperties() ) {
PropertyInfo P = T.GetProperty(m.Name);
switch ( Type.GetTypeCode(P.PropertyType) ) {
case TypeCode.String :
if ( P.GetValue(o, null) == null )
P.SetValue(o, String.Empty, null);
break;
case TypeCode.DateTime :
if ( (DateTime)P.GetValue(o, null) == DateTime.MinValue )
P.SetValue(o, EntityTools.dtDef, null);
break;
}
}
}
full code is here
It could be rewrittent to consider the entity type and so on...
Add a base class:
public class CallBase
{
protected CallBase()
{
Initialize();
}
protected abstract void Initialize();
}
Add the partial class implementation in another file
public partial class Call: CallBase
{
protected override void Initialize();
{
...
}
}
The drawback is that the Initialization method will be called before the all collection creature.
I'm using StructureMap to resolve references to my repository class. My repository interface implements IDisposable, e.g.
public interface IMyRepository : IDisposable
{
SomeClass GetById(int id);
}
An implementation of the interface using Entity Framework:
public MyRepository : IMyRepository
{
private MyDbContext _dbContext;
public MyDbContext()
{
_dbContext = new MyDbContext();
}
public SomeClass GetById(int id)
{
var query = from x in _dbContext
where x.Id = id
select x;
return x.FirstOrDefault();
}
public void Dispose()
{
_dbContext.Dispose();
}
}
Anyway as mentioned I'm using StructureMap to resolve IMyRepository. So when, where and how should I call my dispose method?
WARNING: please note that my views have changed, and you should consider the following advise outdated. Please see this answer for an updated view: https://stackoverflow.com/a/30287923/264697
While DI frameworks can manage lifetime of objects for you and some could even dispose objects for you after you're done using with them, it makes object disposal just too implicit. The IDisposable interface is created because there was the need of deterministic clean-up of resources. Therefore, in the context of DI, I personally like to make this clean-up very explicit. When you make it explicit, you've got basically two options: 1. Configure the DI to return transient objects and dispose these objects yourself. 2. Configure a factory and instruct the factory to create new instances.
I favor the second approach over the first, because especially when doing Dependency Injection, your code isn't as clean as it could be. Look for instance at this code:
public sealed class Client : IDisposable
{
private readonly IDependency dependency;
public Client(IDependency dependency)
{
this. dependency = dependency;
}
public void Do()
{
this.dependency.DoSomething();
}
public Dispose()
{
this.dependency.Dispose();
}
}
While this code explicitly disposes the dependency, it could raise some eyebrows to readers, because resources should normally only be disposed by the owner of the resource. Apparently, the Client became the owner of the resource, when it was injected.
Because of this, I favor the use of a factory. Look for instance at this example:
public sealed class Client
{
private readonly IDependencyFactory factory;
public Client(IDependencyFactory factory)
{
this.factory = factory;
}
public void Do()
{
using (var dependency = this.factory.CreateNew())
{
dependency.DoSomething();
}
}
}
This example has the exact same behavior as the previous example, but see how the Client class doesn't have to implement IDisposable anymore, because it creates and disposes the resource within the Do method.
Injecting a factory is the most explicit way (the path of least surprise) to do this. That's why I prefer this style. Downside of this is that you often need to define more classes (for your factories), but I personally don't mind.
RPM1984 asked for a more concrete example.
I would not have the repository implement IDisposable, but have a Unit of Work that implements IDisposable, controls/contains repositories and have a factory that knows how to create new unit of works. With that in mind, the above code would look like this:
public sealed class Client
{
private readonly INorthwindUnitOfWorkFactory factory;
public Client(INorthwindUnitOfWorkFactory factory)
{
this.factory = factory;
}
public void Do()
{
using (NorthwindUnitOfWork db =
this.factory.CreateNew())
{
// 'Customers' is a repository.
var customer = db.Customers.GetById(1);
customer.Name = ".NET Junkie";
db.SubmitChanges();
}
}
}
In the design I use, and have described here, I use a concrete NorthwindUnitOfWork class that wraps an IDataMapper that is the gateway to the underlying LINQ provider (such as LINQ to SQL or Entity Framework). In sumary, the design is as follows:
An INorthwindUnitOfWorkFactory is injected in a client.
The particular implementation of that factory creates a concrete NorthwindUnitOfWork class and injects a O/RM specific IDataMapper class into it.
The NorthwindUnitOfWork is in fact a type-safe wrapper around the IDataMapper and the NorthwindUnitOfWork requests the IDataMapper for repositories and forwards requests to submit changes and dispose to the mapper.
The IDataMapper returns Repository<T> classes and a repository implements IQueryable<T> to allow the client to use LINQ over the repository.
The specific implementation of the IDataMapper holds a reference to the O/RM specific unit of work (for instance EF's ObjectContext). For that reason the IDataMapper must implement IDisposable.
This results in the following design:
public interface INorthwindUnitOfWorkFactory
{
NorthwindUnitOfWork CreateNew();
}
public interface IDataMapper : IDisposable
{
Repository<T> GetRepository<T>() where T : class;
void Save();
}
public abstract class Repository<T> : IQueryable<T>
where T : class
{
private readonly IQueryable<T> query;
protected Repository(IQueryable<T> query)
{
this.query = query;
}
public abstract void InsertOnSubmit(T entity);
public abstract void DeleteOnSubmit(T entity);
// IQueryable<T> members omitted.
}
The NorthwindUnitOfWork is a concrete class that contains properties to specific repositories, such as Customers, Orders, etc:
public sealed class NorthwindUnitOfWork : IDisposable
{
private readonly IDataMapper mapper;
public NorthwindUnitOfWork(IDataMapper mapper)
{
this.mapper = mapper;
}
// Repository properties here:
public Repository<Customer> Customers
{
get { return this.mapper.GetRepository<Customer>(); }
}
public void Dispose()
{
this.mapper.Dispose();
}
}
What's left is an concrete implementation of the INorthwindUnitOfWorkFactory and a concrete implementation of the IDataMapper. Here's one for Entity Framework:
public class EntityFrameworkNorthwindUnitOfWorkFactory
: INorthwindUnitOfWorkFactory
{
public NorthwindUnitOfWork CreateNew()
{
var db = new ObjectContext("name=NorthwindEntities");
db.DefaultContainerName = "NorthwindEntities";
var mapper = new EntityFrameworkDataMapper(db);
return new NorthwindUnitOfWork(mapper);
}
}
And the EntityFrameworkDataMapper:
public sealed class EntityFrameworkDataMapper : IDataMapper
{
private readonly ObjectContext context;
public EntityFrameworkDataMapper(ObjectContext context)
{
this.context = context;
}
public void Save()
{
this.context.SaveChanges();
}
public void Dispose()
{
this.context.Dispose();
}
public Repository<T> GetRepository<T>() where T : class
{
string setName = this.GetEntitySetName<T>();
var query = this.context.CreateQuery<T>(setName);
return new EntityRepository<T>(query, setName);
}
private string GetEntitySetName<T>()
{
EntityContainer container =
this.context.MetadataWorkspace.GetEntityContainer(
this.context.DefaultContainerName, DataSpace.CSpace);
return (
from item in container.BaseEntitySets
where item.ElementType.Name == typeof(T).Name
select item.Name).First();
}
private sealed class EntityRepository<T>
: Repository<T> where T : class
{
private readonly ObjectQuery<T> query;
private readonly string entitySetName;
public EntityRepository(ObjectQuery<T> query,
string entitySetName) : base(query)
{
this.query = query;
this.entitySetName = entitySetName;
}
public override void InsertOnSubmit(T entity)
{
this.query.Context.AddObject(entitySetName, entity);
}
public override void DeleteOnSubmit(T entity)
{
this.query.Context.DeleteObject(entity);
}
}
}
You can find more information about this model here.
UPDATE December 2012
This an an update written two years after my original answer. The last two years much has changed in the way I try to design the systems I'm working on. Although it has suited me in the past, I don't like to use the factory approach anymore when dealing with the Unit of Work pattern. Instead I simply inject a Unit of Work instance into consumers directly. Whether this design is feasibly for you however, depends a lot on the way your system is designed. If you want to read more about this, please take a look at this newer Stackoverflow answer of mine: One DbContext per web request…why?
If you want to get it right, i'd advise on a couple of changes:
1 - Don't have private instances of the data context in the repository. If your working with multiple repositories then you'll end up with multiple contexts.
2 - To solve the above - wrap the context in a Unit of Work. Pass the unit of work to the Repositories via the ctor: public MyRepository(IUnitOfWork uow)
3 - Make the Unit of Work implement IDisposable. The Unit of Work should be "newed up" when a request begins, and therefore should be disposed when the request finishes. The Repository should not implement IDisposable, as it is not directly working with resources - it is simply mitigating them. The DataContext / Unit of Work should implement IDispoable.
4 - Assuming you are using a web application, you do not need to explicitly call dispose - i repeat, you do not need to explicitly call your dispose method. StructureMap has a method called HttpContextBuildPolicy.DisposeAndClearAll();. What this does is invoke the "Dispose" method on any HTTP-scoped objects that implement IDisposable. Stick this call in Application_EndRequest (Global.asax). Also - i believe there is an updated method, called ReleaseAllHttpScopedObjects or something - can't remember the name.
Instead of adding Dispose to IMyRepository, you could declare IMyRepository like this:
public interface IMyRepository: IDisposable
{
SomeClass GetById(int id);
}
This way, you ensure all repository will call Dispose sometimes, and you can use the C# "using" pattern on a Repository object:
using (IMyRepository rep = GetMyRepository(...))
{
... do some work with rep
}