InsertOnSubmit and InsertAllOnSubmit
In This Topic
As it was already said, all CUD operations are performed during calls to the SubmitChanges method (and only then - all other manipulations with entity objects are 'deferred'). Thus, to save an object you've just created, you have to inform a DataContext instance about this intention (obviously, DataContext itself cannot - and shouldn't - react on any invocation of an entity object constructor). The main way this is done is via the InsertOnSubmit or InsertAllOnSubmit method of the Devart.Data.Linq.Table class:
CrmDemoDataContext context =
new CrmDemoDataContext() { Log = Console.Out };
Product newProduct = new Product()
{
ProductID = 7418,
ProductName = "Twain Mark. Adventures of Tom Sawyer",
CategoryID = 2,
UnitName = "unit",
InStock = 50,
Price = 35,
Discontinued = 0
};
context.Products.InsertOnSubmit(newProduct);
context.SubmitChanges();
Dim context As New CrmDemoDataContext() With { _
.Log = Console.Out _
}
Dim newProduct As New Product() With { _
.ProductID = 7418, _
.ProductName = "Twain Mark. Adventures of Tom Sawyer", _
.CategoryID = 2, _
.UnitName = "unit", _
.InStock = 50, _
.Price = 35, _
.Discontinued = False _
}
context.Products.InsertOnSubmit(newProduct)
context.SubmitChanges()
In this sample, we do the following:
- Create a new Product entity. At this point, the new object has no relation to the data context.
- 'Order' DataContext to persist this entity via the InsertOnSubmit method. Now the context tracks the newProduct object, and 'knows' that it should be saved to the database at the nearest SubmitChanges call.
- Invoke SubmitChanges. This is the point when the context does save the entity (and would perform all other CUD operations - provided there would be any). We enable logging when creating the context so that you can check the generated INSERT command and the moment when it is executed.
The InsertAllOnSubmit method does the same as InsertOnSubmit with the only difference that it takes a collection of entity objects instead of a single one.