Null reference exception on insert of derived class - what am I doing wrong?
Posted: Thu 05 Mar 2020 05:35
The code below attempts to add an object to a MySQL database using EntityDeveloper 6.6.857 in Visual Studio 2019. The code is very simple and shown below. A null reference exception is thrown upon calling InsertOnSubmit. The stack trace doesn't say much. Casting to the base class doesn't fix the problem. Could this be a bug in EntityDeveloper? Thanks -
Here is the code:
Code: Select all
at Devart.Data.Linq.Table.f(Object A_0)
at Devart.Data.Linq.Table`1.InsertOnSubmit(TEntity entity)
at DevartEntityFrameworkBugDemo.Demo.Run()
Code: Select all
static class Demo
{
public static void Run()
{
Context.DataContext dataContext = new Context.DataContext();
// [1] This works fine
Context.Item item = new Context.Item();
item.ID = Guid.NewGuid(); // This is the primary key, and cannot be null
item.ItemName = "Table"; // Just a nullable field
item.Description = "Flat and level"; // Another nullable field
dataContext.Items.InsertOnSubmit(item); // No problem here
dataContext.SubmitChanges();
// [2] But this doesn't
EnhancedItem enhancedItem = new EnhancedItem(Guid.NewGuid(), "Bookcase", "For books");
// This throws a null reference exception:
dataContext.Items.InsertOnSubmit(enhancedItem);
// This doesn't fix ths problem
//Context.Item castVersion = (Context.Item)enhancedItem;
//dataContext.Items.InsertOnSubmit(castVersion);
// This doesn't fix the problem
//dataContext.Items.InsertOnSubmit((Context.Item)enhancedItem);
// (We never get here)
dataContext.SubmitChanges();
}
/// <summary>
/// The EnhancedItem class derives from the class created by EntityDeveloper
/// </summary>
public class EnhancedItem : Context.Item
{
public EnhancedItem(Guid id, string itemName, string description)
{
ID = id;
ItemName = itemName;
Description = description;
}
}
}