木子屋 Dnawo's BLOG

使用Entity Framework做数据导入出错一例

👤 dnawo 📅 2013-03-20 👁 4184 👍 0 💬 0 🔄 来源:本站原创
使用Entity Framework将一批存放在文本文件中的数据导入SQL Server,运行发现当某条数据导入出错时,后面的数据全都报错,代码简化如下:

using (testContext context = new testContext())
{
    Person person = null;
    for (int i = 1; i <= 10; i++)
    {
        try
        {
            if (i == 5)
            {
                person = new Person() { Name = "name" + "".PadRight(20, 'a') }; //超长出错
            }
            else
            {
                person = new Person() { Name = "name" + i };
            }

            context.People.Add(person);
            context.SaveChanges();
        }
        catch { }
    }
}

程序运行后数据库中只有4条记录,原因是出错的记录一直存在于context.People集合中,所以后面调用SaveChanges时都会出错,解决方法:如果记录可以忽略,从集合中移除记录:

using (testContext context = new testContext())
{
    Person person = null;
    for (int i = 1; i <= 10; i++)
    {
        try
        {
            if (i == 5)
            {
                person = new Person() { Name = "name" + "".PadRight(20, 'a') }; //超长出错
            }
            else
            {
                person = new Person() { Name = "name" + i };
            }

            context.People.Add(person);
            context.SaveChanges();
        }
        catch
        {
            [color=Red]context.People.Remove(person);[/color]
        }
    }
}

评论(0)

暂无评论。

验证码
评论需审核通过后显示
← 上一篇 jQuery判断对象是否存在 下一篇 → jQuery事件绑定方法bind、 live、delegate和…