简体   繁体   中英

Entity Framework DbSet throws NullReferenceException

I try to post some values into my mysql database with the entity framework . I'm able to connect to my database successfully. But, after I try to add some values, I've got an NullReferenceException error.

Here's my code:

public class MysqlContext: DbContext
{
    public DbSet<Test> Test { get; set; }

    public MysqlContext(): base("MysqlDefaultConnection")
    {
        Database.Connection.Open();
        var t = new Test { Name = "test", Id = 0 };
        Test.Add(t);
        SaveChanges();
    }
}

[Table("test")]
public class Test
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
}

And this is my configuration of my entity framework:

<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>

<connectionStrings>
<add name="MysqlDefaultConnection" connectionString="server=localhost;user id=dev;password=****;database=****" providerName="MySql.Data.MySqlClient" />

<entityFramework>
<defaultConnectionFactory type="MySql.Data.Entity.MySqlConnectionFactory, MySql.Data.Entity.EF6" />
<providers>
  <provider invariantName="MySql.Data.MySqlClient" type="MySql.Data.MySqlClient.MySqlProviderServices, MySql.Data.Entity.EF6" />
</providers>

Finally this is my table description from my database:

CREATE TABLE `test` (
`Id` int(11) NOT NULL AUTO_INCREMENT,
`Name` varchar(45) NOT NULL,
PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8

So, if I try to connect to my database, everything is okay. After I try to add my entity into the DbSet I'll get an exception.

It behaves the same way if you try this code not in the DbContext constructor?

public class MysqlContext: DbContext
{
    public DbSet<Test> Test { get; set; }

    public MysqlContext(): base("MysqlDefaultConnection")
    {

    }
}

[Table("test")]
public class Test
{
    [Key]
    public int Id { get; set; }
    public string Name { get; set; }
}

public void Main()
{
  var myContext = new MysqlContext();
  var t = new Test { Name = "test", Id = 0 };    
  myContext.Set<Test>.Add(t);
  myContext.SaveChanges();
}

I believe this is because you are doing this in the contractor. At this stage I would assume Test property is not initialised to a value yet. Try run your test code later in the application lifecycle after MysqlContext has been initialized.

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