[英]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.