I am working with EF 6 and Lazy loading.
class MainPrograme
{
static void Main(string[] args)
{
ProgramContext _dbContext = new ProgramContext();
_dbContext.Programs.Add(new Program
{
SecondProgram = new SecondProgram
{
Title = "Demo"
}
});
_dbContext.SaveChanges();
var item = _dbContext.Programs.Find(1);
}
}
Once I disable lazy loading with
Configuration.LazyLoadingEnabled = false;
It works fine. No relational objects are loaded. item.SecondProgram
is null
. Perfect. However when I delete the database, my db initiation sets up a new db and then lazy loading is not working. If I run the above program again, then lazy loading works fine again. Do you guys have any idea why ? Thanks.
Here is my constructor
public ProgramContext()
: base("Data Source=xxx;")
{
Configuration.LazyLoadingEnabled = false;
if (!Database.Exists())
{
Task.Run(InitializeDatabase).Wait();
}
}
If database does not exist, InitializeDatabase will setup the db and if I do a db query in the same context instance, lazy loading fails. If I create a new context object and query db via that, lazy loading works.
Update -
Below is my full console program. Run it and check SecondProgram property if the item. It is not null. Lazy loading not worked there. Then run the program again without deleting the database and check SecondProgram property again. Is is null as expected. Why is was not null in the first run ?
class MainPrograme
{
static void Main(string[] args)
{
ProgramContext _dbContext = new ProgramContext();
_dbContext.Programs.Add(new Program
{
SecondProgram = new SecondProgram
{
Title = "Demo"
}
});
_dbContext.SaveChanges();
var item = _dbContext.Programs.Find(1);
}
}
public class Program
{
public int Id { get; set; }
public string Title { get; set; }
public virtual ICollection<SecondProgram> SecondPrograms { get; set; }
public virtual SecondProgram SecondProgram { get; set; }
}
public class SecondProgram
{
public int Id { get; set; }
public string Title { get; set; }
}
public class ProgramContext : DbContext
{
public ProgramContext()
: base("Data Source=XXX;Initial Catalog=MyContainer;Integrated Security=True;")
{
Configuration.LazyLoadingEnabled = false;
}
public DbSet<Program> Programs { get; set; }
}