simbada simbada - 1 month ago 5
C# Question

getting error when saving entity inside an iterator

I am simply adding student to database by iterating through collection of type list

(i.e. Items)
. Items is not strongly typed here. I am getting this from somewhere else. So i need to construct Student object from it before writing it to SQL. It has student information.

It works fine for me as long as all fields validation okay.

However, if first item in the list has validation error
(i.e. Age required field in Student model)
, i get error which is fine. But for the second item i have valid Age value but still getting validation error for previous item.

try
{
foreach (var item in Items)
{
Student student = new Student
{
StudentId = item.Id,
Age = item.Age,
Description = item.Description
};

_context.Student.Add(student);
_context.SaveChanges();
}
}
catch (MyCustomValidationException ex)
{
//// catch it and log it
}


Is it something related the first item still attached to context?
How do i get rid of that? All i want to save items in DB by iterating through list whichever pass validation.

Items

public class Items
{
public string Id {get;set;}
public string Age {get; set;}
public string Description {get;set;}
}


This is how it is populated

items.Add(
new Items
{
new Items {Id = 1, Age = null, Description = "ABC"},
new Items {Id = 1, Age = 12, Description = "ABC"}
}
)

Answer

The problem is that you have a required field Age in Studentbut you are providing a null value for it and it fails to insert in database.

You should validate the data you want to insert to database.

foreach (var item in Items)
{
    Student student = new Student
    {
        StudentId = item.Id,
        Age = item.Age,
        Description = item.Description
    };

    if (student.IsValid())
    {
        _context.Student.Add(student);
    } // else do something with invalid data! maybe warn user or log it ...
}
_context.SaveChanges();

add IsValid to Student class

public bool IsValid()
{
    if (string.IsNullOrWhiteSpace(this.Age))
    {
        return false;
    }

    return true;
}

What happens??

You add an invalid Student to context by calling _context.Student.Add(student);. Every time you call _context.SaveChanges(); it tries to insert added Students to database. You get the error until you remove invalid Student. It is not a good idea to call SaveChanges because it will hit the database every time you call it and it adds extra overhead. However if you want to check the validity one by one by calling SaveChanges() and get exception you can try this.

foreach (var item in Items)
{
    Student student = new Student
    {
        StudentId = item.Id,
        Age = item.Age,
        Description = item.Description
    };

    _context.Student.Add(student);

    try
    {
        _context.SaveChanges();
    }
    catch (MyCustomValidationException ex)
    {
        _context.Student.Remove(student);
    }
}