0

I have the following one to many table as below. I am experiencing issue when it comes to editing the existing rows with the following code. Please understand that I am pretty new to the ET relationship, so any detailed explanation would be greatly appreciated. Why it is returning null values?

enter image description here

public void UpdateReportGroup(TReportHeaderModel model)
    {

        if (model.THeaderTitle == null)
        {
            throw new Exception("Report Group Title must be filled in");

        }

        if (model.THeaderTitle.Length <= 0)
        {
            throw new Exception("A Report Group Title must be filled in.");

        }
        using (var connection = new TReportEntitiesConnection())
        {

            var header = connection.THeaders.SingleOrDefault(f => f.ID == model.ID);
            var reports = connection.TReport.Where(f => f.THeaderID == model.ID);
            connection.TReport.RemoveRange(reports);
            foreach (var urls in model.TReports)
            {
                connection.TReport.Add(new TReport()

                {
                    TReportName = urls.name,
                    URL = urls.url,
                });
            }
            connection.THeaders.Add(header);
            connection.SaveChanges()      

        }
    }

Everytime, I debug it,it is giving null values for the 'TReport' table. My create new rows works perfectly with the following code. Meaning, I am returning the correct form with correct field names.

public void CreateReport(TReportHeaderModel model)
        {


            if (model.THeaderTitle == null)
            {
                throw new Exception("Report Group Title must be filled in");

            }

            if (model.THeaderTitle.Length <= 0)
            {

                throw new Exception("A Report Group Title must be filled in.");

            }

                using (var connection = new TReportEntitiesConnection())

                {
                    var header = new THeader()
                    {
                        ClientID = model.ClientID,

                        THeaderTitle = model.THeaderTitle,
                        RowNumber = model.RowNumber
                    };


                    foreach (var urls in model.TReports)
                    {

                        header.TReports.Add(new TReport()
                        {

                            TReportName = urls.name,
                            URL = urls.url


                        });

                    }

                    connection.THeaders.Add(header);
                    connection.SaveChanges();

                }

        }

As you can see, I am following DI pattern, and therefore I am calling these two methods in my controller as below:

[HttpPost]
        public ActionResultModel CreateReportAPI([FromBody] TReportHeaderModel model) //attempt 3
        {

            try {
                if (ModelState.IsValid)
                {
                    var isValid = _tReportingService.HeadernameExists(model.THeaderTitle);

                    if (!isValid)

                    {
                        Console.WriteLine("it does not exist");
                        var user = this.GetCurrentUserAccount();
                        model.ClientID = user.SelectedClient.ID;

                        _tReportingService.CreateReport(model);

                    }

                    else //Update method comes till here and it goes //straight to the error
                    {

                        Console.WriteLine("it exists");
                        var user = this.GetCurrentUserAccount();
                        model.ClientID = user.SelectedClient.ID;

                        _tReportingService.UpdateReportGroup(model);

                    }
                }


                return new ActionResultModel()
                {

                    Success=true, 
                    Message="Report Group Successfully Saved."


                };




            }
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Gerle Batde
  • 183
  • 3
  • 21
  • Try adding a ToList() after the Where statement for the TReport retrieval. – master2080 Nov 06 '17 at 07:35
  • @master2080 I did. it is still giving me error. – Gerle Batde Nov 06 '17 at 14:22
  • I am getting error message reading 'Validation failed for one or more entities. See 'EntityValidationErrors' property for more details'. – Gerle Batde Nov 06 '17 at 15:28
  • Googling that error linked me to this question: https://stackoverflow.com/questions/7795300/validation-failed-for-one-or-more-entities-see-entityvalidationerrors-propert .Try that and see if it gives an error that is helpful. – master2080 Nov 06 '17 at 15:54

1 Answers1

0

I guess it would be the last time I'd posting questions here as I understood that it takes you nowhere if you just ask so I'd rather research more and keep trying it until I got it so here I am answering my own question as I'd solved it.

As the model gets generated from WebApi which is completely detached from ET, I am loading the database first and compare which children have been added, deleted & updated. Here is an example of perfect one to many relationship's update/delete.

  using (var connection = new TReportEntitiesConnection())
            {

                var header = connection.THeaders.Include("TReports").SingleOrDefault(f => f.ID == model.ID);

                if (header != null)
                {
                    header.THeaderTitle = model.THeaderTitle; //update parent 
                }
                foreach (var existingChild in header.TReports.ToList())
                {

                    if (!model.TReports.Any(c => c.ID == existingChild.ID))
                        connection.TReport.Remove(existingChild);

                }
                foreach (var url in model.TReports)
                {
                    var existingChild = header.TReports
                        .Where(c => c.ID == url.ID)
                        .SingleOrDefault();


                    if (existingChild != null)
                    { //update child
                        connection.Entry(existingChild).CurrentValues.SetValues(url);
                    }
                    else
                    {
                        var newChild = new TReport
                        {
                            TReportName = url.name,
                            URL = url.url,
                        };

                        header.TReports.Add(newChild);
                    }
                }
                connection.SaveChanges();
            }
Gerle Batde
  • 183
  • 3
  • 21