I have 4 classes: 1 Machine has many Groups, 1 Group has many Units, 1 Unit has many Components
Now I want the component to have a foreign key of the MachineId to make it easier to search te database later on, but i cant make it work.
public class Machine
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public uint MachineId { get; set; }
public virtual List<Group> Groups { get; set; } = new List<Group?>();
}
public class Component
{
[Key, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public uint ComponentId { get; set; }
public virtual Unit Unit { get; set; }
public uint? UnitId { get; set; }
public virtual Machine Machine { get; set; }
public uint? MachineId { get; set; }
}
DatabaseContext:
public class DatabaseContext : DbContext
{
public DatabaseContext(DbContextOptions options) : base(options)
{
}
public DbSet<Machine> Machines { get; set; }
public DbSet<Group> Groups { get; set; }
public DbSet<Unit> Units { get; set; }
public DbSet<Component> Components { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<Component>()
.HasOne(m => m.Machine)
.WithOne()
.HasForeignKey<Component>(c => c.MachineId)
.OnDelete(DeleteBehavior.NoAction);
}
}
DatabaseInitializer:
Machine machine = new Machine
{
Name = "MCTC",
Connected = true,
Active = true,
};
context.Machines.Add(machine);
context.SaveChanges();
Group group = new Group
{
Name = "Group 1",
Index = 0,
Present = true,
};
machine.Groups.Add(group);
context.SaveChanges();
Unit unit = new Unit
{
Name = "Unit 1",
Index = 0,
Present = true,
UnitType = "MB Balance",
};
machine.Groups[0].Units.Add(unit);
context.SaveChanges();
Component component = new Component
{
Name = "Component 1",
Index = 0,
Present = true,
ComponentType = "random"
};
machine.Groups[0].Units[0].Components.Add(component);
context.SaveChanges();
Last "context.SaveChanges()" gives me:
---> Microsoft.Data.SqlClient.SqlException (0x80131904): Cannot insert the value NULL into column 'MachineId', table 'MCSmartDb.dbo.Components'; column does not allow nulls. INSERT fails.
Please help...