如何使用Linq to SQL将对象添加到数据库?

Jos*_*ton 3 c# linq-to-sql

我正在尝试学习LINQ to SQL,我能够查询数据库并获取IQueryable并操纵我从中检索的对象.但我不知道如何将新对象添加回数据库或原始IQueryable.

private DataContext db;
private IQueryable<ActionType> action;

public void BuildQuery(string connection) {
    db = new DataContext(connection);
    action = db.GetTable<ActionType>().Select(a=>a);

    ActionType at = new ActionType();
    at.Name = "New Action Type";

    // What now? action.add(at) || db.GetTable<ActionType>.add(at); ??
}
Run Code Online (Sandbox Code Playgroud)

如果你不知道正确的条款,搜索是一件令人费解的事情.而且我找不到任何能够完全按照我的要求去做的例子.

那么,我该如何将新对象添加到查询/数据库中呢?

mar*_*c_s 9

要插入新创建的"ActionType"实例,需要将对象添加到数据上下文(并在Linq-to-SQL beta期间将"add"重命名为"InsertOnSubmit"),然后在数据上下文中调用SubmitChanges:

public void BuildQuery(string connection) {
    db = new DataContext(connection);
    action = db.GetTable<ActionType>().Select(a=>a);

    ActionType at = new ActionType();
    at.Name = "New Action Type";

    // What now? action.add(at) || db.GetTable<ActionType>.add(at); ??
    db.ActionTypes.InsertOnSubmit(at);
    db.SubmitChanges();
}
Run Code Online (Sandbox Code Playgroud)

这里这篇博客为什么你应该使用InsertOnSubmitAttach.

  • 不应该是这样的:db.ActionTypes.InsertOnSubmit(at); (2认同)