2

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();
    }

2 Answers 2

3

This is by design, you can do two things here:

  1. You can look up the existing command category from the DB and set that as the property (as this object is 'attached' to the DB context, it won't create a new one).

  2. Just set the ID of the command category on the command.

e.g.

newCommand.CommandCategory = dbContext.CommandCategories.Find("8C0D0E31-950E-4062-B783-6817404417D4");

or

newCommand.CommandCategoryId = new Guid("8C0D0E31-950E-4062-B783-6817404417D4");

At the minute, it is seeing a new command category (not attached) so is trying to create it.

2
  • 1
    This makes sense but it certainly seems awkward. On a larger object, with multiple one-to-many relationships and a many-to-many relationship, this is really going to be quite complex to manage. Definitely not impossible to do, just not the small amount of code I am used to.
    – Piercy
    Sep 4, 2019 at 13:14
  • If just setting the IDs, then it's not too bad, but you run the risk of getting FK errors on save if they don't exist.
    – Paddy
    Sep 4, 2019 at 14:28
1

EF doesn't perform InsertOrUpdate checks. Entities are tracked by a DbContext as either Added or Updated. If you interact with a tracked entity or "Add" an entity to the DbContext, all untracked related entities will be recognized as Added, resulting in an insert.

The simplest advice I can give is to give EF the benefit of the doubt when it comes to entities and don't try to premature optimize. It can save headaches.

using (var dbContext = new EfContext())
{
    var newCommand = Add(dbContext);
    AddWithExisting(newCommand, dbContext);

    dbContext.SaveChanges();
    Console.WriteLine("Hello World!");
}

private static command Add(EfContext dbContext)
{
    var newCommand = new Command
    {
        Id = Guid.NewGuid(), // Should either let DB set this by default, or use a Sequential ID implementation.
        Name = "set timeout",
        CommandString = "timeout:500;"
    };
    Guid commandCategoryId = new Guid("8C0D0E31-950E-4062-B783-6817404417D4");
    var commandCategory = dbContext.CommandCategory.Where(x => x.CommandCategoryId == commandCategoryId);
    if(commandCategory == null)
        commandCategory = new CommandCategory 
        { 
            Id = commandCategoryId,
            Name = "Configuration"
        };

    newCommand.CommandCategory = commandCategory;
    dbContext.Command.Add(command);
    return command;
}
private static Command AddWithExisting(Command command, EfContext dbContext)
{
    var newCommand = new Command 
    {
        Id = Guid.NewGuid(),
        Name = "set URL",
        CommandString = "url:www.stackoverflow.com",
        CommandCategory = command.CommandCategory
    };
    dbContext.Commands.Add(newCommand);
    return newCommand;
}

So what's changed here?

First the DbContext reference is Disposable, so it should always be wrapped with a using block. Next, we create the initial Command, and as a safety measure to avoid an assumption we search the context for an existing CommandCategory by ID and associate that, otherwise we create the command category and associate it to the Command. 1-to-many relationships do not need to be bi-directional, and even if you do want bi-directional relationships you don't typically need to set both references to each other if the mappings are set up correctly. If it makes sense to ever load a CommandCategory and navigate to all commands using that category then keep it, but even to query all commands for a specific category, that is easy enough to query from the command level. Bi-directional references can cause annoying issues so I don't recommend using them unless they will be really necessary. We return the new command object back from the first call, and pass it into the second. We really only needed to pass the reference to the commandcategory loaded/created in the first call, but in case it may make sense to check/copy info from the first command, I used this example. We create the new additional command instance and set it's command category reference to the same instance as the first one. I then return the new command as well. We don't use that reference to the second command. The important difference between this and what you had tried is that the CommandCategory here points to the same reference, not two references with the same ID. EF will track this instance as it is associated/added, and wire up the appropriate SQL.

Lastly note that the SaveChanges call is moved outside of the two calls. Contexts generally should only ever save changes once in their lifetime. Everything will get committed together. Having multiple SaveChanges is usually a smell when developers want to manually wire up associations when keys are autogenerated by a DB. (Identity or defaults) Provided relationships are mapped correctly with navigation properties and their FKs, EF is quite capable of managing these automatically. This means that if you set up your DB to default your Command IDs to newsequentialid() for instance and tell EF to treat the PK as an Identity column, EF will handle this all automatically. This goes for associating those new PKs as FKs to related entities as well. No need to save the parent record so the parent ID can be set in the child entities, map it, associate them, and let EF take care of it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.