MySQLでEntityFrameworkを使用していますが、データを挿入しようとするたびにNullReferenceExceptionが発生します。
- コマンドを作成することでデータを直接挿入できますが、EntityFrameworkを使用すると爆発します。
- Entity Frameworkはテーブルから選択するか、テーブルを更新するので、おそらくこれは主キーと関係があります
次の例外は、SaveChanges()メソッドからスローされます。
failed: System.NullReferenceException : Object reference not set to an instance of an object.
at MySql.Data.Entity.ListFragment.WriteSql(StringBuilder sql)
at MySql.Data.Entity.SelectStatement.WriteSql(StringBuilder sql)
at MySql.Data.Entity.InsertStatement.WriteSql(StringBuilder sql)
at MySql.Data.Entity.SqlFragment.ToString()
at MySql.Data.Entity.InsertGenerator.GenerateSQL(DbCommandTree tree)
at MySql.Data.MySqlClient.MySqlProviderServices.CreateDbCommandDefinition(DbProviderManifest providerManifest, DbCommandTree commandTree)
at System.Data.Common.DbProviderServices.CreateCommandDefinition(DbCommandTree commandTree)
at System.Data.Common.DbProviderServices.CreateCommand(DbCommandTree commandTree)
at System.Data.Mapping.Update.Internal.UpdateTranslator.CreateCommand(DbModificationCommandTree commandTree)
at System.Data.Mapping.Update.Internal.DynamicUpdateCommand.CreateCommand(UpdateTranslator translator, Dictionary`2 identifierValues)
at System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator translator, EntityConnection connection, Dictionary`2 identifierValues, List`1 generatedValues)
at System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
at System.Data.EntityClient.EntityAdapter.Update(IEntityStateManager entityCache)
at System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options)
at System.Data.Objects.ObjectContext.SaveChanges()
EF 5
public decimal CreateAlertNotification2(ulong alertServiceId, Alerting.alert_service_notification_type notificationType, string recipientName, string recipientEndpoint)
{
using (risk_fleetEntities dbContext = new risk_fleetEntities())
{
var newNotification = new alert_service_notification();
newNotification.sys_alert_service_id = alertServiceId;
newNotification.name = recipientName;
newNotification.notification_type = Enum.GetName(typeof(Alerting.alert_service_notification_type), notificationType);
newNotification.recipient = recipientEndpoint;
dbContext.alert_service_notification.AddObject(newNotification);
dbContext.SaveChanges();
return newNotification.id;
}
}
MySQL 5
CREATE TABLE `alert_service_notification` (
`id` bigint(20) unsigned AUTO_INCREMENT PRIMARY KEY,
`sys_alert_service_id` bigint(20) unsigned NOT NULL,
`notification_type` ENUM("SMS", "Email"),
`name` CHAR(50),
`recipient` CHAR(50),
FOREIGN KEY (`sys_alert_service_id`) REFERENCES `alert_service`(`id`)
);