I had a problem trying to add object from dto.
I have a DTO like this
public class CustomerCourseSessionDto : IDto
{
public int Id { get; set; }
public int? ConnectorId { get; set; }
public List<SomeObject>? SomeObject { get; set; }
public List<OtherObject>? OtherObject { get; set; }
}
and I'm trying to insert this DTO sent from the UI. I'm using a loop(foreach) for this, but it didn't feel right to me.
Maybe entityframework suggests a method for this, idk...
Other objects are like this
public class SomeObject: IEntity
{
public int Id { get; set; }
public int? ConnectorId { get; set; }
}
public class OtherObject: IEntity
{
public int Id { get; set; }
public int? ConnectorId { get; set; }
}
Thanks for the suggestions.
Here is where I use the loop:
[TransactionScopeAspect]
public IResult AddWithDto(CustomerCourseSessionDto courseSessionDto)
{
foreach (var item in courseSessionDto.Participants)
{
_someObjectService.Add(item);
}
foreach (var item in courseSessionDto.Lessons)
{
_otherObjectService.Add(item);
}
_customerCourseSessionDal.Add(new CustomerCourseSession
{
Id = courseSessionDto.Id,
CustomerCourseId = courseSessionDto.CustomerCourseId,
});
return SuccessResult with message ;
}
TransactionScopeAspect. JustsomeContext.CourseSession.Add(sessionAndAll);is enough. That will add all related objects in theAddedstate. A DbContext is already a Unit-of-Work, so whenSaveChangesis called all changes will be persisted in a single database transactionTransactionScopeAspectisn't an EF Core attribute nor would it matter. All pending changes are saved withSaveChanges. There are multiple "services" which means that either EF isn't used at all, or it's used incorrectly. At best those "services" are just wrappers over an injected DbContext