如何通过“插入”或“更新”填充表

时间:2014-08-17 05:15:14

标签: c# .net linq bltoolkit

我通过BLToolkit访问数据库。我的一张桌子有:

  • 字段:Id,TeamId,PlayerId,Val1,Val2
  • 主键 - 字段ID,自动增量
  • 复合唯一键,由2个字段TeamId和PlayerId
  • 组成
  • 数据字段Val1,Val2

我已经创建了对象列表:

List<MyObj> objs = new []{
    new MyObj{TeamId=2, PlayerId=3, Val1=1234, Val2=111},
    new MyObj{TeamId=2, PlayerId=4, Val1=2345, Val2=444},
    new MyObj{TeamId=2, PlayerId=5, Val1=3456, Val2=666},
    };

我可以使用

将所有这些对象插入到DB中
db.InsertBatch(objs);

但是一些具有相同复合键的记录可能已经存在于DB中,因此我希望自动执行这些对象的更新,而不是INSERT。

我知道BLToolkit有InsertOrUpdate和InsertOrReplace,但它们都只使用了1个对象。

我有什么办法可以将1个请求中的对象列表替换为DB?

谢谢。

P.S。实际上,我在objs中列出的数据不是以编程方式创建的,它们最近是基于查询其他表从DB中提取的。也许与获取这些数据一起,我应该尝试获取现有对象的ID并使用此信息来决定插入或更新?

1 个答案:

答案 0 :(得分:0)

如果您的对象来自另一个表,您可以执行左连接来排序需要插入或更新的对象:

var useInsertQuery = from o in db.OtherObjs
            join m in db.MyObjs on new { m.TeamId, m.PlayerId } equals new { o.TeamId, o.PlayerId } into moJoin
            from mo in moJoin.DefaultIfEmpty()
            let useInsert = (mo == null)
            // MyObj f(OtherObj otherObj) creates your updated MyObj value
            group f(m,o) by useInsert into g;
var useInsertDictionary = useInsertQuery.ToDictionary(g => g.Key, g => g.ToArray());

MyObj[] objs;
if (useInsertDictionary.TryGetValue(true, out objs))
    db.InsertBatch(objs);
if (useInsertDictionary.TryGetValue(false, out objs))
    db.Update(objs);