Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
128 views
in Technique[技术] by (71.8m points)

c# - Storing multiple records to database doesnt store all related records

In my dotnet api application I have some functionality which is supposed to store some records to the database using NHibernate and IUnitOfWork. I have the following tables:

Meeting
-------
Id (GUID)
MeetingDate (datetime)
Organizer (GUID) FK -> Organizer.Id

Organizer
--------
ID (GUID)
Name

My endpoint accepts an object of type MeetinghDto from which a Meeting is created through a MeetingFactory containing the Organizer as a property. The following code shows the definition of said objects.

[Class(NameType = typeof(Meeting), Table = "Meeting")]
public class Meeting
{
    [Id(0, Name = "Id")]
    public virtual Guid? Id { get; set; }

    [Property]
    public virtual DateTime MeetingDate { get; set; }

    [ManyToOne(Cascade = Cascade.AllDeleteOrphan, NotNull = false)]
    public virtual Organizer Organizer { get; set; }
}

[Class(NameType = typeof(Organizer), Table = "Organizer")]
public class Organizer
{
    [Id(0, Name = "Id")]
    public virtual Guid? Id { get; set; }

    [Property]
    public virtual string Name { get; set; }
}

I'm using the following code to store multiple meetings at once.

public class StoreMeetingService : IStoreMeetingService
{
    private readonly IUnitOfWork _unitOfWork;
    private readonly IMeetingRepository _meetingRepository;

    public StoreMeetingService(IUnitOfWork unitOfWork, IMeetingRepository meetingRepository)
    {
        _unitOfWork = unitOfWork;
        _meetingRepository = meetingRepository;
    }

    public void SaveMeetings(IList<Meetings> meetings)
    {
        using(_unitOfWork.BeginTransaction())
        {
            try
            {
                foreach(var meeting in meetings)
                {
                    _meetingRepository.Create(meeting); 
                }
                
                _unitOfWork.Commit();
            }
            catch(Exception exception)
            {
                _unitOfWork.Rollback();
            }
        }
    }
}

public class MeetingRepository : Repository<Meeting>, IMeetingRepository
{

}

When reviewing the data that is stored I only see records for Organizer and none for Meeting.

I have already tried to register the StoreMeetingService as Scoped instead of Singleton but to no avail.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to MLink Developer Q&A Community for programmer and developer-Open, Learning and Share
...