I am having difficulty inserting data with its related entities.
public class Status : Entity, IAggregateRoot
{
//other properties
public readonly List<Video> _videos;
public readonly List<Photo> _photos;
}
--
public class Log : Entity, IAggregateRoot
{
//other properties
public readonly List<Video> _videos;
public readonly List<Photo> _photos;
public readonly List<Sound> _audios;
}
--
public class Photo : Entity, IAggregateRoot
{
//other properties
public string Type { get; set; }
public int TypeId { get; set; }
}
Basically, A status object can have zero or more videos or pictures. A log object can also have zero or more videos, sound or pictures. Below is the fluent api code used to achieve this:
class LogEntityTypeConfiguration : IEntityTypeConfiguration<Log>
{
public void Configure(EntityTypeBuilder<Log> logConfiguration)
{
logConfiguration.HasMany(b => b.Videos)
.WithOne()
.HasForeignKey("TypeId")
.OnDelete(DeleteBehavior.Cascade);
logConfiguration.HasMany(b => b.Photos)
.WithOne()
.HasForeignKey("TypeId")
.OnDelete(DeleteBehavior.Cascade);
logConfiguration.HasMany(b => b.Audios)
.WithOne()
.HasForeignKey("TypeId")
.OnDelete(DeleteBehavior.Cascade);
}
}
--
public void Configure(EntityTypeBuilder<Status> statusConfiguration)
{
statusConfiguration.HasMany(b => b.Videos)
.WithOne()
.HasForeignKey("TypeId")
.OnDelete(DeleteBehavior.Cascade);
statusConfiguration.HasMany(b => b.Photos)
.WithOne()
.HasForeignKey("TypeId")
.OnDelete(DeleteBehavior.Cascade);
}
This builds just fine, the image below shows the generated foreign keys.
I have got a log repository class, when trying to insert a log object, i get the following error:
System.Data.SqlClient.SqlException (0x80131904): The INSERT statement conflicted with the FOREIGN KEY constraint
"FK_Photos_Statuses_TypeId". The conflict occurred in database "xxxx", table "dbo.Statuses", column 'Id'
public async Task<Log> AddAsync(Log log, LogFiles files)
{
var strategy = _context.Database.CreateExecutionStrategy();
await strategy.ExecuteAsync(async () => {
using (var txn = _context.Database.BeginTransaction())
{
try
{
if (log.IsTransient())
{
_context.Logs.Add(log);
_context.SaveChanges();
if (files.Video != null)
{
Video vid = new Video();
vid = files.Video;
log._videos.Add(vid);
}
if(files.Picture != null)
{
Photo ph = new Photo();
ph = files.Picture;
log._photos.Add(ph);
}
if(files.Audio != null)
{
Sound aud = new Sound();
aud = files.Audio;
log._audios.Add(aud);
}
_context.SaveChanges();
txn.Commit();
}
}
catch (Exception ex)
{
txn.Rollback();
}
}
});
return log;
}
I also don't understand why the foreign key of the status object is showing up among the error list, when i'm trying to insert a log object??
p.s if you have a better way i could model the relationship please share.