Here is the thing bugging me, I have 2 entities --- 'Master' and 'Slave', let me list them first:
public class Master
{
public Guid Id {get;set;}
public virtual ICollection<Slave> Slaves { get; set; }
public virtual Slave ParentSlave { get; set; }
}
class Slave
{
public Guid Id { get; set; }
public Guid ParentMasterId { get; set; }
public Master ParentMaster { get; set; }
public Guid? ChildMasterId { get; set; }
public Master ChildMaster { get; set; }
}
Basically,
- Master have list of Slaves;
- Slave should belong to a Master(Parent);
- Slave have another Master(Child) which then can have list of Slaves;
Here comes corresponding data mapping class,
class MasterDataMap : EntityTypeConfiguration<Master>
{
public MasterDataMap()
{
HasKey(i => i.Id);
HasOptional(o => o.ParentSlave).WithRequired(o=>o.ChildMaster);
ToTable("Master");
}
}
class SlaveDataMap : EntityTypeConfiguration<Slave>
{
public SlaveDataMap()
{
HasKey(i => i.Id);
HasRequired(o => o.ParentMaster).WithMany(m => m.Slaves).HasForeignKey(k=>k.ParentMasterId).WillCascadeOnDelete(true);
HasRequired(o => o.ChildMaster).WithOptional(d => d.ParentSlave);
ToTable("Slave");
}
}
Those 2 entities can pass the EF model validation without any problem, and tables can be created successfully during end-to-end test, after running following code,
for (var idx = x; idx <= xx; idx++)
{
topMaster.Slaves.Add(new Slave
{
Id = Guid.NewGuid(),
ChildMaster = new Master
{
Id = Guid.NewGuid(),
}
});
}
topMaster and its slaves all been inserted into tables, childmaster(s) also been inserted, but they have not associated with topMaster's Slaves which means 'ChildMaster' are null and 'ChildMasterId' are empty guid.
I don't know what is wrong with data mapping classes to cause this issue.