Delete all position in DbContext from BindingSource.List using Entity (EF6) - vb.net

I have DbContext with table named:base.books
and BindingSource from LINQ query with records which I want to delete using RemoveRange.
Dim query = From books
In base.books
Where //some conditions
Select books.id, books.name,
Dim BooksSource As New BindingSource
BooksSource.DataSource = query.ToList
DataGridView_Books.DataSource = BooksSource.DataSource
After some changes in DataGridView_Books I want delete all positions from DataGridView_Books in base.books.
I imagine it that way:
listA=BooksSource.DataSource.List
''listB=convert(listA)
base.books.RemoveRange(listB)
base.books.SaveChanges()
but I do not know how to replace convert (I mean: 'System.Collections.IList' to 'System.Collections.IEnumerable')
Thanks.

Related

Copy two dataTables to another table in vb.net

I have two dataTables which I want to union to make one final dataTable.
Both are results of different functions.
I tried this :
dtfinal = dt1.Copy()
dtfinal = dt2.Copy()
But here dt2 data is replaced by dt1. What should be used to get union of both into the final dt.
You can use DataTable.Merge:
Dim allTables() As DataTable = {dt1, dt2}
Dim dtfinal = new DataTable("dtfinal")
dtfinal.BeginLoadData() ' Turns off notifications, index maintenance, and constraints while loading data
For Each t As DataTable in allTables
dtfinal.Merge(t) ' same as table.Merge(t, false, MissingSchemaAction.Add)
Next
dtfinal.EndLoadData()
If you don't have primary keys specified you could end up with repeating rows where you actually want to merge them. Then either specify the PKs or use this method i have provided here(needs conversion from C#):
Combining n DataTables into a Single DataTable

SqlDataAdapter.Fill(DataGridView.DataSource) duplicates all rows

Simple question:
When I call SqlDataAdapter.Fill(DataGridView.DataSource) the second time after initially creating first Data it does not update the contained rows. It simply adds all rows returned by the select command to my DataGridView.
If I call it a third, fourth (so on) it will also just add the returned rows.
Am I understanding the .Fill(DataTable) function wrong? How do I update the already existing DataTable correctly? Which line of code is responsible for that?
Turns out it has to be a code problem;
DataGridView1.AutoGenerateColumns = False
Dim sql = "select * from myTable"
oDtSource = New DataTable
oAdapter = New SqlDataAdapter
oCon = sqlCon("serverName\Instance", "myDataBase") ' Returns a SqlConnection
oCmd = New SqlCommand(sql, oCon)
oCon.Open()
oDtSource.Clear()
oAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey
oAdapter.SelectCommand = oCmd
oAdapter.Fill(oDtSource)
DataGridView1.DataSource = oDtSource
For refreshing I use oAdapter.Fill(oDtSource)
The PrimaryKey is set in the database
From MSDN:
You can use the Fill method multiple times on the same DataTable. If a
primary key exists, incoming rows are merged with matching rows that
already exist. If no primary key exists, incoming rows are appended to
the DataTable.
So either define a primary key or clear the table first.
Dim table = CType(DataGridView.DataSource, DataTable)
table.Clear()
' fill ...
To define primary key(s) manually read this. To let it create automatically if they are defined in the database you need to set the MissingSchemaAction to AddWithKey:
' ...
dataAdapter.MissingSchemaAction = MissingSchemaAction.AddWithKey
' fill ...
The edit code doesnt show the PrimaryKey being defined for the DataTable. This will configure the DataAdapter to perform updates and enabled refreshing the DataTable. The code uses MySQL but the Provider objects all work the same in this regard:
' persistant form level vars
Private daSample As MySqlDataAdapter
Private dtSample As DataTable
...
Elsewhere:
' there are caveats with WHERE clauses
Dim sql = "SELECT Id, Name, Country, Animal FROM SAMPLE WHERE Color = 'onyx'"
' using the ctor overload, no need for a DbCommand or Connection object
daSample = New MySqlDataAdapter(sql, MySQLConnStr)
' initialize the CommandBuilder, get other commands
Dim cbSample = New MySqlCommandBuilder(daSample)
daSample.UpdateCommand = cbSample.GetUpdateCommand
daSample.InsertCommand = cbSample.GetInsertCommand
daSample.DeleteCommand = cbSample.GetDeleteCommand
dtSample = New DataTable()
daSample.FillSchema(dtSample, SchemaType.Source)
dtSample.PrimaryKey = New DataColumn() {dtSample.Columns("id")}
daSample.Fill(dtSample)
dgv1.DataSource = dtSample
To pick up changes made to the db from other client apps:
daSample.Fill(dtSample)
Initial display:
After I change a row to "onyx" from a UI browser and Update the changed row shows up:
WHERE clauses can be a bit of an issue. Since it restricts the subset of data pulled back, Update is only going to compare rows in the new result set. So, if I change an onlyx row to "blue" it wont be removed.
One solution is to use .DefaultView.RowFilter on the table, but that can slow things down since it requires returning all rows to the client to be filtered there. Its not perfect.

VB.NET tabledapter query insert into from another dataset

I have a situation where I want to Insert into access DB table from MS SQL table.
Same columns and everything.
I have both data sets and both table adapter. I can do what ever I want inside each dataset - any manipulation but I cannot insert from one table to another.
I tried creating an Insert query for destination tableadapter but I cannot get the from working. Tried linking, nothing works.
Searched for days, simply cannot find it.
Thank you for your answer. Can you help me on my example. I'm having trouble setting this up. This is what i got:
Dim myToTableTableAdapter As FirstDataSetTableAdapters.ToTableTableAdapter
myToTableTableAdapter = New FirstDataSetTableAdapters.ToTableTableAdapter()
Dim myFromTableTableAdapter As SecondDataSetTableAdapters.FromTableTableAdapter
myFromTableTableAdapter = New SecondDataSetTableAdapters.FromTableTableAdapter()
myFromTableTableAdapter = myToTableTableAdapter.Clone
'but it doesnt work from here`
What I wanted to do is:
For each drfrom As DataRow In myFromTableTableAdapter.GetData
myToTableTableAdapter.InsertInto(drfrom.item(column01), drfrom.item(column02), drfrom.item(andSoOn))
Next
But it seem to me that this would take so much longer then a "Insert Into From Select" script.
You cannot insert a row from one table into another table, but there are a couple of ways to do what you want. One way (a little verbose) is this:
' sets it up with same schema but empty rows
mOutTable = inTable.Clone
' Now insert the rows:
For Each rowIn In inTable.Rows
r = mOutTable.NewRow()
For Each col In inTable.Columns
r(col.ColumnName) = rowIn(col.ColumnName)
Next
mOutTable.Rows.Add(r)
Next
mOutTable.AcceptChanges
A second way, which is more concise, is this:
outTable = inTable.Clone
For Each inRow As DataRow In inTable.Rows
outTable.LoadDataRow(inRow.ItemArray, False)
End If
outTable.AcceptChanges
Note that both inTable and outTable are ADO.NET DataTable objects. You cannot implement my suggestion on the DataAdapter objects. You must use the DataTable objects. Each DataTable can be associated with a DataAdapter in the standard fashion for ADO.NET:
Dim t as New DataTable()
a.Fill(t);
where a is the ADO.NET DataAdapter. I hope this helps!
Jim

How do I fill a DataSet or a DataTable from a LINQ Stored procedure?

I’m trying to fill data table from the sp. but it’s seems not right. Any ideas about my approach
Dim dt As New DataTable
Using EdSQL As New MyEntities
Dim Query = From St In EdSQL.MySp(Prameter).AsEnumerable
Select St
dt=Query.......
End Using
I think you need something like this...
Dim EdSQL As New My Entities
Dim query = From st In EdSQL.MySp(Parameter).AsEnumerable
Select St
gvStockEDI.DataSource = query.ToList()
gvStockEDI.DataBind()

nHibernate select query?

I have an ado.net statement I want to convert to use NHibernate:
Dim sql As New StringBuilder()
sql.AppendLine("SELECT r.RoleId, r.RoleName ")
sql.AppendLine("FROM dbo.aspnet_Roles r ")
sql.AppendLine("WHERE r.RoleId IN ")
sql.AppendLine(" (select roleID from dbo.MenuRole where menuId = #MenuId) ")
sql.AppendLine("Order By r.RoleName")
later, I populate the parameter with:
cmd.Parameters.AddWithValue("#MenuId", menuId)
Considering I want to return an: IList(Of AspnetRole)
and I'm using:
Dim managerFactory As IManagerFactory = New ManagerFactory()
Dim roleManager As IAspnetRoleManager = managerFactory.GetAspnetRoleManager()
How do I build and use that query with nHiberate?
(P.S. I am using Codesmithtools and VB.net and VS2008 and SQL Server 2008)
First, you'd have to map the aspnet_roles table and the MenuRole table to their corresponding classes. Once you've mapped them, I'd also map a many-to-one MenuRole property to the AspnetRole class.
Once you've done that the criteria query should look something like this:
Dim c As ICriteria = Session.CreateCriteria(TypeOf(AspnetRole))
c.Add(Restrictions.Eq("Menu.Id", menuId)
return c.List(Of AspnetRole)