如何在Ef中正确插入嵌套对象



我在尝试从dto添加对象时遇到问题。

我有一个类似的DTO

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; }
}

我正在尝试插入从UI发送的这个DTO。我用了一个循环(foreach(,但我觉得不对。

也许实体框架提出了一种方法,idk。。。

其他对象类似于此

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; } 
}

谢谢你的建议。

这是我使用循环的地方:

[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 ;
}

您应该将实体设计为使用外键链接到每个表。

public class CustomerCourseSession
{
public int Id { get; set; } // Primary Key
public string Name { get; set; }
public virtual ICollection<CourseParticipant> Participants { get; set; }
public virtual ICollection<CourseLesson> Lessons { get; set; }
}
public class CourseParticipant
{
public int Id { get; set; }
public int CustomerCourseSessionId { get; set; } // Foreign Key from CustomerCourseSession
// other fields here

public virtual CustomerCourseSession CustomerCourseSession { get; set;}
}

public class CourseLesson
{
public int Id { get; set; }
public int CustomerCourseSessionId { get; set; } // Foreign Key from CustomerCourseSession
// other fields here

public virtual CustomerCourseSession CustomerCourseSession { get; set;}

}

然后你可以打电话给:

var entity = MapDtoToEntity(courseSessionDto);
_dbContext.CustomerCourseSessions.Add(entity);
_dbContext.SaveChanges();

最新更新