即使我们在某些记录中有错误,也要保存记录

时间:2015-04-24 19:58:29

标签: entity-framework

我将来自另一个数据库的大量数据复制到我的数据库,该数据库的结构与我的不同 - 我创建了对象,将它们添加到DbSet并调用SaveChanges()方法。但是如果一条记录无效,那么方法SaveChanges()会抛出错误,并且数据库中不会插入任何记录。我想保存正确的记录 - 我怎样才能在Entity Framework中执行此操作?

DatabaseContext db = new DatabaseContext();

Gifts gift1 = new Gifts();
gift1.Name = "test1";
gift1.Price = 5;
db.Gifts.Add(gift1);

// Here ERROR - because name can't be NULL:
Gifts gift2 = new Gifts();
gift2.Name = null;
gift2.Price = 5;
db.Gifts.Add(gift2);

Gifts gift3 = new Gifts();
gift3.Name = "test3";
gift3.Price = 5;
db.Gifts.Add(gift3);

// .....

DatabaseContext.SaveChanges();

1 个答案:

答案 0 :(得分:0)

只需将代码括在try catch块中,然后单独保存每个实体:

DatabaseContext db = new DatabaseContext();

try{
    Gifts gift1 = new Gifts();
    gift1.Name = "test1";
    gift1.Price = 5;
    db.Gifts.Add(gift1);

    DatabaseContext.SaveChanges();
}
catch{}

// Here ERROR - because name can't be NULL:
try{
    Gifts gift2 = new Gifts();
    gift2.Name = null;
    gift2.Price = 5;
    db.Gifts.Add(gift2);

    DatabaseContext.SaveChanges();
}
catch{}

try{   
    Gifts gift3 = new Gifts();
    gift3.Name = "test3";
    gift3.Price = 5;
    db.Gifts.Add(gift3);

    DatabaseContext.SaveChanges();
}
catch{}