Here are the classes:
public class Parent
{
public int Id { get; set; }
public string Name { get; set; }
public IEnumerable<Child> Childs { get; set; }
public IEnumerable<ParentLog> Logs { get; set; }
}
public class ParentLog
{
public int Id { get; set; }
public DateTime On { get; set; }
public string Note { get; set; }
public int ParentId { get; set; }
public string Name { get; set; }
}
public class Child
{
public int Id { get; set; }
public string Name { get; set; }
public int ParentId { get; set; }
public IEnumerable<ChildLog> Logs { get; set; }
}
public class ChildLog
{
public int Id { get; set; }
public DateTime On { get; set; }
public string Note { get; set; }
public int ChildId { get; set; }
public string Name { get; set; }
public int ParentId { get; set; }
}
In DbContext
:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Parent>().HasMany(a => a.Childs);
modelBuilder.Entity<Parent>().HasMany(a => a.Logs);
modelBuilder.Entity<Child>().HasMany(a => a.Logs);
}
The idea is for log entries for both Parent and Child be saved also, when Parent and Child is saved. This works.
Codes for saving:
DateTime now = DateTime.Now;
foreach (var a in parents)
{
a.Logs = new List<ParentLog>();
a.Logs.Add(new ParentLog
{
On = now,
Note = "Created",
Name = a.Name
});
foreach(var b in a.Childs)
{
b.Logs = new List<ChildLog>();
b.Logs.Add(new ChildLog
{
On = now,
Note = "Created",
Name = b.Name,
ParentId = b.ParentId //not needed with the Accepted Answer.
});
}
}
int recordsAffected = new ParentRepository().SaveParents(parents);
public int SaveParents(List<Parent> items)
{
foreach(var item in items)
{
_db.Parents.Add(item);
}
return _db.SaveChanges();
}
The issue I'm encountering is with the ChildLog.ParentId
. It doesn't have the value of the expected value, which is coming from Child.ParentId
I suppose.
My question, how to resolve it?