I have a very simple database with 2 tables: Test and Tester, Test has an Id and a Name, Tester has an Id a TestName and a TestId. There is a 1 : N connection between the two. What I simply like to do is add a new entry to one of the tables but I got a null reference exception.
I have a class for the context:
public class TestContext : DbContext, ITestContext
{
public DbSet<Test> Tests { get; set; }
public DbSet<Tester> Testers { get; set; }
public TestContext()
: base(){}
public TestContext(DbConnection connection) : base (connection, false)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Configurations.Add(new TestConfiguration());
modelBuilder.Configurations.Add(new TesterConfiguration());
}
}
The two configuration files contains the relations and some restrictions.
And I have an EntityManager class that can add a new entity to one the objects:
private ITestContext _context;
public ObservableCollection<Test> Tests { get; set; }
public ObservableCollection<Tester> Testers { get; set; }
private static EntityManager _instance;
public static EntityManager Instance
{
get { return _instance ?? (_instance = new EntityManager()); }
}
private EntityManager()
{
Tests = new ObservableCollection<Test>();
Testers = new ObservableCollection<Tester>();
Database.DefaultConnectionFactory = new SqlConnectionFactory("System.Data.SqlClient");
connection = Database.DefaultConnectionFactory.CreateConnection(@"Data Source=.;Initial Catalog=Test;Integrated Security=True");
_context = new TestContext(connection);
_context.Tests.Add(new Test {Name = "new Test"});
_context.SaveChanges();
LoadData();
}
private void LoadData()
{
Tests.Clear();
Testers.Clear();
_context.Tests.ToList().ForEach(Tests.Add);
_context.Testers.ToList().ForEach(Testers.Add);
}
So when I try to add the "new test" to the tests I got a null reference exception. And if I leave the add part out it runs perfectly but then I lost the functionalty to add a new entity to a collection. Could someone advise me what could go wrong? Cheers!
_context.Tests? Or is it something insideDbContext?