0

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!

2
  • 1
    What is null? Is it _context.Tests? Or is it something inside DbContext? Commented May 25, 2012 at 14:22
  • DbContext was fine along with the _context.Tests. It throws the null reference exception inside the add function. Commented May 30, 2012 at 6:29

3 Answers 3

1

Hopefully this will help someone...

I've ran into a similar problem, having a NullReferenceException on DbSet.Add and the funny part was that it only happened once for each DbSet called in the controller action. There were three, so after three repeated requests the code succeeded.

REASON: I invoked an async DB read before calling Add and only awaited it at the end. When I moved the await in front of these calls, the issue was gone.

This will cause the problem

var task = UserManager.FindByIdAsync(User.Identity.GetUserId()); // Uses the same DB Context
DbContext.Stages.Add(...);
await task;
Sign up to request clarification or add additional context in comments.

Comments

0

There was a problem in the models, and the configurations. Wrong connection between the tables.

4 Comments

Could you please elaborate on what specifically was wrong? I think I'm having the same problem...
Actually I determined that my problem was threading. I had added an event handler to a DbContext.Set().Local.ToBindingList().ListChanged and was attempting to access the DbContext during the event handler. DbContext.Set() returned null during that execution.
for me, I started over from brick by brick the configuration. And I cant remember unfortunately what exaclt went wrong. But something must have been with the HasOptional(t => t.testers).WithRequired(tr => t.Test) or something like that. The funny thing was I could not determine it during the debug. Just threw an exception with the Add method.
I had the same problem where the Add method would just throw the NullReferenceException. In my case I think it was the fact that DbContext.Set<T>() returned null, but I couldn't figure out why. It appeared to occur when I was trying to access the context in event handlers. When I looked closer, the handlers were on the same thread, so I'm not really sure the explanation for the error.
0

Okay. I ran into this issue as well. For me, it was because I had a WPF application that was attempting to read my EntityState in one of its ICommands while my Entity was being modified by an event trigger. Not sure why this was an issue, as I saw that everything was on the same Dispatcher thread, but by using

System.Windows.Application.Current.Dispatcher.BeginInvoke(new Action(() => MyEntity.MyEntityProperty=SomeValue));

for the code that was in my event, I was able to solve my problem.

Hopefully this helps someone else.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.