简体   繁体   中英

Code-First: Null reference exception when adding an entity to a dbset

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!

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

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;

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM