我正在尝试学习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)
如果你不知道正确的条款,搜索是一件令人费解的事情.而且我找不到任何能够完全按照我的要求去做的例子.
那么,我该如何将新对象添加到查询/数据库中呢?
要插入新创建的"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)
见这里这篇博客为什么你应该使用InsertOnSubmit过Attach.
渣