LESSON 6 OF 19

Foreign Key Failure: Why Does an Insert Fail When the Related Record Is Missing?

Explore invalid foreign keys, required relationships, navigation properties and DeleteBehavior using a practical Order and Customer example.

35 dk 113

Introduction

One of the most common errors when inserting a new Order with Entity Framework Core is a foreign key violation. The exception usually contains the name of a foreign key constraint, a CustomerId value or the related table. This means that the customer referenced by the order does not exist in the database.

In this lesson, we will use Order and Customer entities to examine three problems: an insert failing because of an invalid foreign key, an incorrectly configured required relationship and an inappropriate delete behavior when a customer is removed. We will also see why assigning only a navigation property is not always sufficient and how to design a reliable order creation flow.

Understanding the foreign key relationship

A customer can have many orders. Therefore, the relationship is modeled as one-to-many from Customer and many-to-one from Order. In the database, Orders.CustomerId becomes a foreign key referencing Customers.Id.

The existence of the related record must be protected both at the application level and at the database level. The foreign key constraint requires the value in Orders.CustomerId to exist in Customers.Id. Therefore, when EF Core sends the insert command, the database rejects the operation if the customer is missing.

Entity definitions

public class Customer
{
    public int Id { get; set; }
    public string Name { get; set; } = string.Empty;

    public ICollection<Order> Orders { get; set; } = new List<Order>();
}

public class Order
{
    public int Id { get; set; }
    public DateTime CreatedAt { get; set; }

    public int CustomerId { get; set; }
    public Customer Customer { get; set; } = null!;
}

Because CustomerId is a non-nullable int, the relationship is required. Every order must belong to a customer. A customer may exist without orders, but an order cannot exist without a customer.

Configuring the relationship explicitly

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Order>()
        .HasOne(order => order.Customer)
        .WithMany(customer => customer.Orders)
        .HasForeignKey(order => order.CustomerId)
        .IsRequired()
        .OnDelete(DeleteBehavior.Restrict);
}

Here, Order is the dependent entity and Customer is the principal entity. IsRequired() explicitly states that every order requires a customer. DeleteBehavior.Restrict prevents a customer with existing orders from being deleted directly. This is often safer when order history must be preserved.

Problem 1: Inserting an invalid CustomerId

The following code uses a value that does not exist in the database as CustomerId.

var order = new Order
{
    CustomerId = 999999,
    CreatedAt = DateTime.UtcNow
};

dbContext.Orders.Add(order);
await dbContext.SaveChangesAsync();

If there is no customer with ID 999999 in the Customers table, SaveChangesAsync throws a DbUpdateException. The Add call only places the entity in the change tracker; foreign key validation commonly occurs when the SQL command is executed by the database.

For this reason, it is normal to see the error on the SaveChangesAsync line rather than on the Add line. The inner exception may contain details about the constraint violation reported by SQL Server or by the selected database provider.

Flawed approach

public async Task<int> CreateOrderAsync(int customerId)
{
    var order = new Order
    {
        CustomerId = customerId,
        CreatedAt = DateTime.UtcNow
    };

    dbContext.Orders.Add(order);
    await dbContext.SaveChangesAsync();

    return order.Id;
}

This code trusts the supplied customerId. If the value comes from an HTTP request, a message queue or an external system, the referenced customer may not exist. The caller may then receive a generic database error instead of a meaningful validation response.

Corrected approach: validate the relationship first

public async Task<int> CreateOrderAsync(int customerId)
{
    var customerExists = await dbContext.Customers
        .AnyAsync(customer => customer.Id == customerId);

    if (!customerExists)
    {
        throw new InvalidOperationException(
            "The specified customer does not exist.");
    }

    var order = new Order
    {
        CustomerId = customerId,
        CreatedAt = DateTime.UtcNow
    };

    dbContext.Orders.Add(order);
    await dbContext.SaveChangesAsync();

    return order.Id;
}

AnyAsync checks only for existence, so it can be more appropriate than loading every customer column. This avoids unnecessary data transfer. However, the check alone does not eliminate race conditions. Another operation could delete the customer between the check and the insert. Therefore, the database foreign key constraint must remain in place, and DbUpdateException should still be handled around SaveChangesAsync.

Problem 2: Why is assigning a navigation property not always enough?

EF Core can synchronize a navigation property and its foreign key through the change tracker. However, it matters whether the assigned object represents an existing database row or a newly created entity.

Risky usage

var order = new Order
{
    CreatedAt = DateTime.UtcNow,
    Customer = new Customer
    {
        Id = 42,
        Name = "Existing Customer"
    }
};

dbContext.Orders.Add(order);
await dbContext.SaveChangesAsync();

The application may assume that customer 42 already exists. However, this object is not a previously loaded representation of the existing row; it is a newly instantiated entity. When EF Core processes the entity graph, it may treat the customer as new and attempt to insert it as well. If the key is already used, a primary key error may occur. If it is not used, an unexpected customer row may be created.

In another scenario, the navigation property may be assigned while CustomerId still contains a different value. This can happen with entities from different context instances, detached graphs or code that changes the foreign key and navigation values independently.

Safe navigation property usage

var customer = await dbContext.Customers
    .SingleOrDefaultAsync(customer => customer.Id == customerId);

if (customer is null)
{
    throw new InvalidOperationException(
        "A customer is required to create an order.");
}

var order = new Order
{
    CreatedAt = DateTime.UtcNow,
    CustomerId = customer.Id,
    Customer = customer
};

dbContext.Orders.Add(order);
await dbContext.SaveChangesAsync();

In this example, the customer was loaded by the same DbContext. EF Core knows that it is an existing tracked entity. Alternatively, only the foreign key can be assigned, which avoids loading the customer object:

var order = new Order
{
    CustomerId = customerId,
    CreatedAt = DateTime.UtcNow
};

dbContext.Orders.Add(order);
await dbContext.SaveChangesAsync();

This approach transfers less data. Still, an application-level check with AnyAsync or FindAsync is recommended when the caller should receive a meaningful validation message.

Problem 3: What happens when DeleteBehavior is wrong?

The correct action when deleting a customer who has orders depends on the business rule. Three common options are:

  • Cascade: Deleting the customer also deletes related orders. It may be appropriate when dependents have no independent lifecycle, such as some test or temporary data.
  • Restrict: The customer cannot be deleted while related orders exist. This is safer when order history must be retained.
  • SetNull: The customer relationship is removed when the customer is deleted. This requires a nullable foreign key and must be allowed by the business rules.

If orders are important for financial or audit purposes, Cascade can be dangerous. Deleting one customer could unintentionally delete thousands of orders.

Delete behavior with Restrict

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Order>()
        .HasOne(order => order.Customer)
        .WithMany(customer => customer.Orders)
        .HasForeignKey(order => order.CustomerId)
        .IsRequired()
        .OnDelete(DeleteBehavior.Restrict);
}
var customer = await dbContext.Customers
    .SingleOrDefaultAsync(customer => customer.Id == customerId);

if (customer is null)
{
    throw new InvalidOperationException("Customer was not found.");
}

dbContext.Customers.Remove(customer);

try
{
    await dbContext.SaveChangesAsync();
}
catch (DbUpdateException)
{
    throw new InvalidOperationException(
        "A customer with existing orders cannot be deleted.");
}

For a better user experience, the application can also check for existing orders before attempting the delete. However, another operation may occur between the check and the delete. The database constraint must therefore remain the final protection layer.

Making SQL and error analysis easier

When diagnosing foreign key problems, it is useful to inspect the SQL generated by EF Core. In a development environment, simple logging can be enabled with LogTo.

optionsBuilder
    .EnableDetailedErrors()
    .LogTo(Console.WriteLine);

In production, avoid writing sensitive values to logs. The SQL output can show the INSERT INTO Orders command and its CustomerId parameter. This helps determine whether the application is sending the expected ID.

Common mistakes

  • Using a CustomerId without checking that it exists.
  • Creating a new Customer object with the same ID instead of loading the existing entity.
  • Assuming that assigning a navigation property always fixes the foreign key value.
  • Making a required foreign key nullable and leaving the business rule unclear.
  • Enabling Cascade without considering the risk of deleting order history.
  • Removing the database foreign key constraint and relying only on application validation.
  • Returning a generic error without logging or interpreting the DbUpdateException.

Short practice exercise

  1. Create the Customer and Order entities. Make Order.CustomerId required.
  2. Configure the relationship with DeleteBehavior.Restrict and create a migration.
  3. Try to insert an order with a missing customer ID. Observe that the failure occurs during SaveChangesAsync.
  4. Write a service method that validates the relationship with AnyAsync.
  5. Create an order for a customer and then try to delete that customer. Convert the resulting exception into a meaningful business error.
  6. Enable LogTo, inspect the generated SQL and verify the CustomerId sent during the insert.

Conclusion

A foreign key error is usually not a random EF Core failure. It is an important data-integrity signal showing that the related record referenced by the application does not exist. A reliable design explicitly models the relationship, configures required relationships correctly, validates the related entity before inserting and preserves the database constraint.

Navigation properties are convenient, but they are not always sufficient when working with detached entities, incorrect IDs or newly created graphs. The choice of DeleteBehavior is also more than a technical setting: it affects order-history retention, customer deletion policy and the risk of data loss. When these decisions are aligned with business rules, EF Core applications become more reliable, easier to understand and easier to troubleshoot in production.

Sources