简体   繁体   中英

How can I find out the line that caused the error in entity framework?

I am adding a range of data in my database.

IList<Data> items = //326 rows of data

using(MyDataContext c = new MyDataContext()){
     c.MyTable.AddRange(items);
     c.SaveChanges();
}

But sometimes it throws DbUpdateException like following.

ORA-12899: value too large for column SM.TB.NAME (actual:265, max: 255)

But I can not understand which line of data? How can I find it?

I should return a warning message to user, this data is invalid.

You should validate the data before trying to save it. Perhaps something like this:

// Find the invalid items
var invalidItemIds = items
    .Where(x => x.Name.Length > 255)
    .Select(x => x.Id);

if (invalidItemIds.Any())
{
    // If there is invalid items, handle it the way of your choice
    throw new Exception($"The name is too long for items: {string.Join(",", invalidItemIds)}");
}

The Name column size of SM.TB DB table that is accociated with my MyTable of dbcontext is too small - 255 chars, you need 265 at least. You have to change property Name of MyTable class

[Column(TypeName = "VARCHAR2")]
 [StringLength(512, MaximumLength = 255)]
public string Name{ get; set; }

or fluent Api

modelBuilder.Entity<MyTable>()
  .Property(e => e.Name).HasColumnType("VARCHAR2").HasMaxLength(255);

If you realy need more than 255 change the number to Max are you expecting.

Migrate table to database. Or you can change it directly in OracleDb if you know how. Use this script

ALTER TABLE SM.TB
MODIFY Name VARCHAR2( 512 );

As a workaround just add Name length check code (see the answer of @kaffekopp) and cut a string to 255 if it's possible

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM