How to add an object to a database using Linq to SQL?

I am trying to learn LINQ to SQL, and I can query the database and return IQueryable and process the objects that I extract from this. But I do not know how to add a new object back to the database or to the original 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); ??
}

It is surprisingly hard to find if you do not know the right conditions. And I cannot find examples that do exactly what I want them to do.

So, how do I add adding new objects to a query / database?

+3
source share
4 answers

"ActionType", ( "add" "InsertOnSubmit" - Linq-to-SQL), 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();
}

, InsertOnSubmit Attach.

+9
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";

   //There must be a table like ActionType and it seems ActionTypes when calling it ith   // db
   db.ActionTypes.InsertOnSubmit(at);
   db.SubmitChanges();
}

:

+2

Now all you have to do is send your changes back to the database:

db.Attach(at);
db.SubmitChanges();
0
source

I would wrap the DataContext in a using statement - it guarantees that it will be deleted when the operation is completed.

Like this:

public void BuildQuery(string connection) 
{
    using (var 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();
    }
}
0
source

Source: https://habr.com/ru/post/1716874/


All Articles