在C#中使用Linq to Sql,有什么方法可以自动截断太长的数据吗? [英] Using Linq to Sql in C#, is there any way I can automatically truncate too-long data?

查看:168
本文介绍了在C#中使用Linq to Sql,有什么方法可以自动截断太长的数据吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我正在将数据从一个数据库导入另一个数据库.大约有5,000条记录(所以没有什么可笑的,但足够小以至于无法引起注意).有没有一种简单的方法可以自动截断太长的数据-特别是varchar字段?我不希望截断保持沉默,因为太长的字段可能需要引起注意,但是如果一个太长的2个字符的名称不会在插入时失败并且抛出一个完全非特定的异常,那将非常好

So, I'm importing data from one database into another. There are about 5,000 records (so nothing ridiculous, but not small enough to eyeball). Is there an easy way to automatically truncate data that is too long - specifically, varchar fields? I don't want truncation to be silent since the too-long fields will likely require attention, but it would be really nice if a name that is 2 characters too long wouldn't fail on insert, and throw a totally non-specific exception.

我要实现的解决方案是将数据截断,插入并记录下来的解决方案.还有其他人做过类似的事情吗?

The solution I'd like to implement is one that will truncate the data, insert it, and log this. Has anyone else done something similar?

推荐答案

Linq2Sql将生成如下属性:

Linq2Sql will generate a property like this:

    [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的函数?只需创建一个具有该名称的函数来进行截断和记录:

See how it calls a function called OnNameChanged? Just create a function with that name to do the truncation and logging:

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

这篇关于在C#中使用Linq to Sql,有什么方法可以自动截断太长的数据吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆