'Will this code run from an inherited EF constructor?
Imagine we have two DbContexts that inherit from EF DbContext as such:
using System.Data.Entity;
using System.Collections.Generic;
namespace myproject.Models
{
public class MyContext : DbContext
{
public MyContext(string nameOrConnectionString) : base(nameOrConnectionString)
{
Database.CommandTimeout = Config.DatabaseCommandTimeout;
Database.SetInitializer<MyContext>(null);
}
public MyContext() : this("name=MyDbContextConnectionString") { }
}
public class MyContext2ReadOnly : MyContext
{
public MyContext2ReadOnly() : base("MyDbContextConnectionStringReadOnly")
{
}
}
}
Now imagine we create an instance of MyContext2ReadOnly().
My question is - will the following line Database.SetInitializer<MyContext>(null); from the parent constructor be valid, or do I have to call it again in the MyContext2ReadOnly() constructor as such(?):
public class MyContext2ReadOnly : MyContext
{
public MyContext2ReadOnly() : base("MyDbContextConnectionStringReadOnly")
{
Database.SetInitializer<MyContext2ReadOnly>(null);
}
}
Solution 1:[1]
I think DbContext is not special when handling inheritance and constructor. So just have a test. I will define a Db to replace DbContext.
public class Db
{
public Db(string s)
{
Console.WriteLine($"Db {s}");
}
}
public class MyContext : Db
{
public MyContext(string nameOrConnectionString) : base(nameOrConnectionString)
{
Console.WriteLine($"MyContext {nameOrConnectionString}");
}
public MyContext() : this("name=MyDbContextConnectionString") { }
}
public class MyContext2ReadOnly : MyContext
{
public MyContext2ReadOnly() : base("MyDbContextConnectionStringReadOnly")
{
Console.WriteLine($"MyContext2ReadOnly");
}
}
//in main
MyContext2ReadOnly myContext2ReadOnly = new MyContext2ReadOnly();
//output
Db MyDbContextConnectionStringReadOnly
MyContext MyDbContextConnectionStringReadOnly
MyContext2ReadOnly
It proves everything in MyContext constructor are called.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Lei Yang |
