在C#中使用Linq to Sql,有什么办法可以自动截断太长的数据吗?

所以,我将数据从一个数据库导入另一个数据库。 大概有5000条记录(所以没什么可笑的,但不足以让人眼前一亮)。 是否有一种简单的方法可以自动截断太长的数据 – 特别是varchar字段? 我不希望截断是静默的,因为太长的字段可能需要注意,但是如果一个2个字符太长的名字在插入时不会失败并且抛出一个完全非特定的exception,那将是非常好的。

我想要实现的解决方案是截断数据,插入数据并记录它。 有没有其他人做过类似的事情?

Linq2Sql将生成如下属性:

[Column(Storage="_Name", DbType="NVarChar(50) NOT NULL")] public string Name { get { return this._Name; } set { if ((this._Name != value)) { this.OnNameChanging(value); this.SendPropertyChanging(); this._Name = value; this.SendPropertyChanged("Name"); this.OnNameChanged(); } } } 

看看它如何调用一个名为OnNameChanged的函数? 只需创建一个具有该名称的函数来执行截断和日志记录:

 void OnNameChanged() { if (Name.Length > 50) { Name = Name.Substring(0, 50); LogSomehow("Name truncated"); } } 

我会做一个扩展迭代器方法,你可以抛出你的查询内联,做这样的事情:

 public static IEnumerable Truncater(this IEnumerable s, int len) { foreach( var str in s ) { if( str.Length > len ) { string outStr = str.Substring(0, len); Console.WriteLine(String.Format("Truncated {0} to {1}", str, outStr)); yield return outStr; } else yield return str; } } 

这是一种更自动的方法。 它会动态地查看每个要插入的列的类型/长度。

像这样用它:

  foreach (object insert in context.GetChangeSet().Inserts) { FindLongStrings(update); } context.SubmitChanges(); 

这里是方法:(它的效率非常低,所以我不会把它留在生产代码中,但是如果你有一次性的转换/导入(听起来就像你那样),它可能就是这样。)

  public static void FindLongStrings(object testObject) { foreach (PropertyInfo propInfo in testObject.GetType().GetProperties()) { foreach (ColumnAttribute attribute in propInfo.GetCustomAttributes(typeof(ColumnAttribute), true)) { if (attribute.DbType.ToLower().Contains("varchar")) { // kinda crude, but it works... string dbType = attribute.DbType.ToLower(); int numberStartIndex = dbType.IndexOf("varchar(") + 8; int numberEndIndex = dbType.IndexOf(")", numberStartIndex); string lengthString = dbType.Substring(numberStartIndex, (numberEndIndex - numberStartIndex)); int maxLength = 0; int.TryParse(lengthString, out maxLength); string currentValue = (string)propInfo.GetValue(testObject, null); // Do your logging and truncation here if (!string.IsNullOrEmpty(currentValue) && currentValue.Length > maxLength) Console.WriteLine(testObject.GetType().Name + "." + propInfo.Name + " " + currentValue + " Max: " + maxLength); } } } }