'I'm trying to add a ninja (entity) to the database using Entity framework and it fails with an inner exception and SqlException. How do I fix this?

I'm trying to add an entity to the database but when I run the console app it fails to save the entity to the database.

Inner Exception 1:

UpdateException: An error occurred while updating the entries. See the inner exception for details.

Inner Exception 2:

SqlException: The INSERT statement conflicted with the FOREIGN KEY constraint "FK_dbo.Ninjas_dbo.Clans_ClanId". The conflict occurred in database "NinjaDomain.DataModel.NinjaContext", table "dbo.Clans", column 'Id'. The statement has been terminated.

ConsoleApp.cs

public class Program
{
    static void Main(string[] args)
    {
        InserNinja();
    }

    private static void InserNinja()
    {
        try
        {
            var ninja = new Ninja
            {
                Name = "MakiniBryan",
                ServedInOniwaban = false,
                DateOfBirth = new DateTime(1993, 09, 30),
                ClanId = 1
            };

            using var context = new NinjaContext();
            context.Database.Log = Console.WriteLine;
            context.Ninjas.Add(ninja);
            context.SaveChanges();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message); 
        }
    }
}

Ninja.cs

public class Ninja
{
    public int Id { get; set; }
    public string Name { get; set; }
    
    public bool ServedInOniwaban { get; set; }
    
    public int ClanId { get; set; }
    public Clan Clan { get; set; }
    public List<NinjaEquipment> Equipment { get; set; } 
    public DateTime DateOfBirth { get; set; }
    
}

Clan.cs

public class Clan
{
    public int Id { get; set; }
    public string ClanName { get; set; }
}

NinjaEquipment.cs

public class NinjaEquipment
{
    public int Id { get; set; }
    public string Name { get; set; }
    public EquipmentType Type { get; set; }
    [Required]
    public Ninja Ninja { get; set; }
}

NinjaContext.cs

public class NinjaContext:DbContext
{
    public DbSet<Ninja> Ninjas { get; set; }
    public DbSet<Clan> Clans { get; set; }
    public DbSet<NinjaEquipment> Equipment { get; set; }
}


Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source