我嘗試將一些值發佈到我的mysql database with the entity framework
。我能夠成功連接到我的數據庫。但是,在我嘗試添加一些值後,我得到了一個NullReferenceException
錯誤。實體框架DbSet拋出NullReferenceException
這裏是我的代碼:
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; }
}
這是我的我的實體框架的配置:
<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>
最後,這是我的表DESCRIPTIO n在我的數據庫:
CREATE TABLE `test` (
`Id` int(11) NOT NULL AUTO_INCREMENT,
`Name` varchar(45) NOT NULL,
PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
所以,如果我嘗試連接到我的數據庫,一切都還好。在我嘗試將實體添加到DbSet後,我會得到一個異常。
哪條線具體拋出,什麼是堆棧跟蹤? – CodeCaster
我在這裏有錯誤:「Test.Add(t);」。這裏是我的堆棧跟蹤:http://pastebin.com/B2yd64Ff – user3149497
在運行代碼之前,您不會給上下文任何機會啓動它自己的屬性。它只是在建造。這是不適合放置這種代碼的地方。它甚至不屬於上下文類中的任何地方。 –