Small amount of context, I have been using NHibernate mapping by code for a few years, the last few months I have started using Entity Framework Core.
I'm trying to understand why I have to null child objects to stop them inserting new records. I'm not sure if its an understanding issue on my part or if this is how Entity Framework works.
I have two classes, Command and CommandCategory. Command has a single CommandCategory and CommandCategory can have many commands. For example, The command "set timeout" would go under the "Configuration" category. Similarly, the "set URL" command would also go under the "Configuration" category.
class Command
{
public Guid Id { get; set; }
public string Name { get; set; }
public string CommandString { get; set; }
public Guid CommandCategoryId { get; set; }
public CommandCategory CommandCategory { get; set; }
}
class CommandCategory
{
public CommandCategory(string id, string name)
{
Id = Guid.Parse(id);
Name = name;
Commands = new List<Command>();
}
public Guid Id { get; set; }
public string Name { get; set; }
public ICollection<Command> Commands { get; set; }
}
My DbContext is setup like so:
class EfContext : DbContext
{
private const string DefaultConnection = "XXXXX";
public virtual DbSet<Command> Command { get; set; }
public virtual DbSet<CommandCategory> CommandCategory { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
optionsBuilder.UseSqlServer(DefaultConnection);
optionsBuilder.EnableSensitiveDataLogging();
}
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Command>()
.HasOne(x => x.CommandCategory)
.WithMany(x => x.Commands);
}
}
Then here is the code that actually runs it all. First I call Add(). Add creates a new Command and adds it to the database. It also creates a CommandCategory called "Configuration" and inserts both correctly.
Next I call AddWithExisting(). This will create a new Command but using the existing CommandCategory. When it tries to add to the database, it first inserts the Command and then it tries to insert the CommandCategory. Because the CommandCategory.Id already exists, and its setup as the primary key, this then fails as it's a duplicate key. To get around this I have to make sure the CommandCategory property on the Command object is set to null. This will then only insert the Command to the database and not the CommandCategory object.
I know usually you wouldn't create a new CommandCategory object, but in this instance I am simulating the object coming up from the client via an ApiController. My application sends data back and forth via WebApi so the object is basically being created new when a request is made.
Nulling the property seems like a strange thing to do, I thought the point of Object-relational mapping was to not have to deal with individual properties like this.
Is this how its supposed to function or am I doing something wrong?
class Program
{
static void Main(string[] args)
{
var dbContext = new EfContext();
Add(dbContext);
AddWithExisting(dbContext);
Console.WriteLine("Hello World!");
}
private static void Add(EfContext dbContext)
{
var newCommand = new Command();
newCommand.Id = Guid.NewGuid();
newCommand.Name = "set timeout";
newCommand.CommandString = "timeout:500;";
var newCommandCategory = new CommandCategory("8C0D0E31-950E-4062-B783-6817404417D4", "Configuration");
newCommandCategory.Commands.Add(newCommand);
newCommand.CommandCategory = newCommandCategory;
dbContext.Command.Add(newCommand);
dbContext.SaveChanges();
}
private static void AddWithExisting(EfContext dbContext)
{
var newCommand = new Command();
newCommand.Id = Guid.NewGuid();
newCommand.Name = "set URL";
newCommand.CommandString = "url:www.stackoverflow.com";
// this uses the same Id and Name as the existing command, this is to simulate a rest call coming up with all the data.
var newCommandCategory = new CommandCategory("8C0D0E31-950E-4062-B783-6817404417D4", "Configuration");
newCommandCategory.Commands.Add(newCommand);
// If i don't null the below line, it will insert to the database a second time
newCommand.CommandCategory = newCommandCategory;
newCommand.CommandCategoryId = newCommandCategory.Id;
dbContext.Command.Add(newCommand);
dbContext.SaveChanges();
}