簡體   English   中英

如何找出導致實體框架錯誤的行?

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

我正在我的數據庫中添加一系列數據。

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

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

但有時它會拋出 DbUpdateException 如下所示。

ORA-12899: 列 SM.TB.NAME 的值太大(實際值:265,最大值:255)

但是我看不懂是哪一行數據? 我怎樣才能找到它?

我應該向用戶返回一條警告消息,此數據無效。

您應該在嘗試保存數據之前驗證數據。 也許是這樣的:

// 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)}");
}

與我的 dbcontext 的 MyTable 關聯的 SM.TB DB 表的 Name 列大小太小 - 255 個字符,您至少需要 265 個字符。 您必須更改 MyTable class 的屬性名稱

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

或流利的 Api

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

如果您確實需要超過 255 個,請將數字更改為您期望的 Max。

將表遷移到數據庫。 或者,如果您知道如何,您可以直接在 OracleDb 中更改它。 使用這個腳本

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

作為一種解決方法,只需添加名稱長度檢查代碼(請參閱@kaffekopp 的答案)並在可能的情況下將字符串剪切為 255

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM