0

I am rather new to the whole programming with C# and I stumbled upon a small problem that I just cannot solve.

I start up the software the code below is programmed into and it is working well until it reaches the SaveChanges call and it throws an error:

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.

I have already attempted to inspect EntityValidationErrors, but it doesn't want to show me any errors at all. So I am turning to you all to find some answers.

//
// GET: /Installningar/FoxImportTidning
public async Task<ActionResult> FoxImportTidning()
{
        Tidning tidning = new Tidning();
        SaveTidningToDatabase("C:/Backup/Prenback/backuptidning.xls");
        return View();
}

//
// POST: /Installningar/FoxImportTidning
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> FoxImportTidning(Tidning Id)
{
        if (ModelState.IsValid)
        {
            db.Entry(Id).State = EntityState.Modified;
            await db.SaveChangesAsync();
            Main.PopulateGlobalInst();
            ViewBag.SaveMsg = "Sparat!";
            return RedirectToAction("Main", "Main", new { Id = Id.Id });
        }

        return View(Id);
}

private ApplicationDbContext databas6 = new ApplicationDbContext();

private string SaveTidningToDatabase(string filePath)
{
        String excelConnString = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0\"", filePath);

        using (OleDbConnection excelConnection = new OleDbConnection(excelConnString))
        {
            using (OleDbCommand cmd = new OleDbCommand("Select * from [backuptidning$]", excelConnection))
            {
                excelConnection.Open();
                var tidningLista = new List<Tidning>();
                databas6.Tidnings.Clear();
                databas6.SaveChanges();

                using (OleDbDataReader dReader = cmd.ExecuteReader())
                    do
                    {
                        while (dReader.Read())
                        {
                            Object[] tidninginfo = new Object[45];
                            int id = Convert.ToInt32(dReader[0]);
                            string namn = Convert.ToString(dReader[1]);
                            string datadir = Convert.ToString(dReader[2]);
                            string adr1 = Convert.ToString(dReader[3]);
                            string adr2 = Convert.ToString(dReader[4]);
                            string regnr = Convert.ToString(dReader[5]);
                            string tel = Convert.ToString(dReader[6]);
                            string pg = Convert.ToString(dReader[7]);
                            string bg = Convert.ToString(dReader[8]);
                            string villkor = Convert.ToString(dReader[9]);
                            int sista_nr = Convert.ToInt32(dReader[10]);
                            int faktavg = Convert.ToInt32(dReader[11]);
                            int vilande = Convert.ToInt32(dReader[12]);
                            int listlopnr = Convert.ToInt32(dReader[13]);
                            int faktnr = Convert.ToInt32(dReader[14]);
                            decimal moms = Convert.ToDecimal(dReader[15]);
                            int avipriskod = Convert.ToInt32(dReader[16]);
                            DateTime? inbetdat = null;
                            try
                            {
                                inbetdat = Convert.ToDateTime(dReader[17]);
                            }
                            catch { }

                            int period = Convert.ToInt32(dReader[18]);
                            string avityp = Convert.ToString(dReader[19]);
                            DateTime? sistavidat = null;

                            try
                            {
                                sistavidat = Convert.ToDateTime(dReader[20]);
                            }
                            catch { }

                            DateTime? fromdatum = null;

                            try
                            {
                                fromdatum = Convert.ToDateTime(dReader[21]);
                            }
                            catch { }

                            DateTime? tomdatum = null;

                            try
                            {
                                tomdatum = Convert.ToDateTime(dReader[22]);
                            }
                            catch { }

                            int fromprennr = Convert.ToInt32(dReader[23]);
                            int tomprennr = Convert.ToInt32(dReader[24]);
                            string databasversion = Convert.ToString(dReader[25]);
                            int nummerperiod = Convert.ToInt32(dReader[26]);
                            int nolastyear = Convert.ToInt32(dReader[27]);
                            int nonextyear = Convert.ToInt32(dReader[28]);
                            string dubbelnummer = Convert.ToString(dReader[29]);
                            bool skrivetik = Convert.ToBoolean(dReader[30]);
                            bool utrmomsavdrag = Convert.ToBoolean(dReader[31]);
                            bool buntning = Convert.ToBoolean(dReader[32]);

                            int pren = Convert.ToInt32(dReader[33]);
                            int betalare = Convert.ToInt32(dReader[34]);
                            int kredit = Convert.ToInt32(dReader[35]);
                            int fornyanr = Convert.ToInt32(dReader[36]);

                            string landskod = Convert.ToString(dReader[37]);
                            DateTime? nästsist = null;

                            try
                            {
                                nästsist = Convert.ToDateTime(dReader[38]);
                            }
                            catch { }

                            string fax = Convert.ToString(dReader[39]);
                            string epost = Convert.ToString(dReader[40]);
                            string hemsida = Convert.ToString(dReader[41]);
                            string bic = Convert.ToString(dReader[42]);
                            string iban = Convert.ToString(dReader[43]);
                            string faktkoll = Convert.ToString(dReader[44]);

                            var tidning = new Tidning();
                            tidning.Id = id;
                            tidning.Namn = namn;
                            tidning.Datadir = datadir;
                            tidning.Adr1 = adr1;
                            tidning.Adr2 = adr2;
                            tidning.Regnr = regnr;
                            tidning.Tel = tel;
                            tidning.Pg = pg;
                            tidning.Bg = bg;
                            tidning.Villkor = villkor;
                            tidning.Sista_nr = sista_nr;
                            tidning.FaktAvg = faktavg;
                            tidning.Vilande = vilande;
                            tidning.Listlopnr = listlopnr;
                            tidning.Faktnr = faktnr;
                            tidning.Moms = moms;
                            tidning.AviPriskod = avipriskod;
                            tidning.InbetDatum = inbetdat;
                            tidning.Period = period;
                            tidning.AviTyp = (AviTyp)Enum.Parse(typeof(AviTyp), avityp, true);
                            tidning.SistAviDatum = sistavidat;
                            tidning.FromDatum = fromdatum;
                            tidning.TomDatum = tomdatum;
                            tidning.FromPrennr = fromprennr;
                            tidning.TomPrennr = tomprennr;
                            tidning.Databasversion = databasversion;
                            tidning.Nummerperiod = nummerperiod;
                            tidning.Nolastyear = nolastyear;
                            tidning.Nonextyear = nonextyear;
                            tidning.Dubbelnummer = dubbelnummer;
                            tidning.Skrivetik = skrivetik;
                            tidning.Utrmomsavdrag = utrmomsavdrag;
                            tidning.Buntning = buntning;
                            tidning.Pren = pren;
                            tidning.Betalare = betalare;
                            tidning.Kredit = kredit;
                            tidning.Fornyanr = fornyanr;
                            tidning.Landskod = landskod;
                            tidning.NastSist = nästsist;
                            tidning.Fax = fax;
                            tidning.Epost = epost;
                            tidning.Hemsida = hemsida;
                            tidning.Bic = bic;
                            tidning.Iban = iban;
                            tidning.Faktkoll = faktkoll;

                            tidningLista.Add(tidning);
                        }
                    } while (dReader.NextResult());
                databas6.Tidnings.AddRange(tidningLista);
                databas6.SaveChanges(); //<--- This is where it goes wrong
                excelConnection.Close();

                return ("hej"); //<--- Do not mind this one
            }
        }
}

If you need any further information, just tell me and I will provide it. The main thing I want is to get this working and this is not the only code giving me this problem, but if this one can be solved, then maybe the other ones can be solved the same way.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
  • 1
    Wrap your SaveChanges in a try/catch. When it fails, you should be able to dig into the exception and see exactly whats causing the validation error. – garethb Jun 13 '17 at 06:38
  • You're using a `select *`, so you must be sure that your `dReader` reads the columns in the right order, did you double/triple check that order ? Also `Object[] tidninginfo = new Object[45];` is unused, is it normal to you ? – Rafalon Jun 13 '17 at 06:50
  • Possible duplicate of [Validation failed for one or more entities. See 'EntityValidationErrors' property for more details](https://stackoverflow.com/questions/7795300/validation-failed-for-one-or-more-entities-see-entityvalidationerrors-propert) – mmushtaq Jun 13 '17 at 06:55
  • @Rafalon I have checked the order that `dReader` is reading the columns and I found that it got all the data it needs, but then upon reaching `SaveChanges()` it is giving me the `Validation failed for one or more entities. See 'EntityValidationErrors' property for more details.` I am beginning to understand what could be the problem, but not sure if it could be that things becomes `null` and is not compatible with it. – Alexander af Skanke Jun 13 '17 at 07:16
  • @mmushtaq I read that link before I posted here and it didn't help me at all. But maybe someone else will have some use for it, so thanks for sharing possible solutions. ^^ – Alexander af Skanke Jun 13 '17 at 07:17
  • this error comes when you are passing null to the column which is been declared not null .... – Rush.2707 Jun 13 '17 at 07:50
  • @Rush.2707 I just checked it and that was the issue! Thank you! – Alexander af Skanke Jun 14 '17 at 06:28
  • you welcome ... Hope you solved that – Rush.2707 Jun 14 '17 at 08:35

2 Answers2

0

This error is caused when you are trying to add invalid data to your database table.

e.g. you are adding string of 100 chars to the table column but in table definition your column has maxlength of 50. in that case value you are adding is invalid as per the column definitions and this error occur.

you should log what properties are causing the error. for that you can use below code:

 catch (System.Data.Entity.Validation.DbEntityValidationException ex)
            {
                Logger.WriteError("{0}{1}Validation errors:{1}{2}", ex, Environment.NewLine, ex.EntityValidationErrors.Select(e => string.Join(Environment.NewLine, e.ValidationErrors.Select(v => string.Format("{0} - {1}", v.PropertyName, v.ErrorMessage)))));
                throw;
            }
Jaimin Dave
  • 1,224
  • 10
  • 18
0

You can catch these errors easily ,using the watch window, without writing much code.

Kindly find the very good solution in the following link

https://stackoverflow.com/a/40732784/3397630

I really inspired in the way that answer was given, with the very good screenshots . Sharing it here with the hope it will be helpful to you and the others.

thanks

KArthik

Karthik Elumalai
  • 1,574
  • 1
  • 11
  • 12