Trackablecollection problem in EF - c#

I newbie in EF.
I have Table A linked together to table B, by passing a primary ID from table A which is a secondary ID on table B Iam trying to retrieve an object from table B.
But I am getting trackableCollection'1[Object name(from table B)]
Any suggestions?
I am trying to retrieve using stored proc
here is the code:
select * from tableB as da
left outer join tableA as cr on da.ID = cr.ID
where da.ID = #d

Related

C# SqlCommandBuilder , CommandUpdate - how to write correct update based on select with outer join tables

I want is to update 2 fields: p.FlagaWaznosci and p.Notatka
My select looks like:
Select DISTINCT p.id,p.Model_Number,p.Product_Name,p.Website_Link,p.Entry_date,p.LastUpdate_date,p.PrzydzialRozmiarow_ID,p.FlagaWaznosci,p.Notatka,pr.NazwaRozmiarowki,wd.LINK_StockX
from Products p with(nolock)
left outer join Widok_Model_Sklep_Stockx_Linki wd with(nolock) on wd.Product_ID = p.id
left outer join PrzydzialRozmiarow pr with(nolock) on pr.id = p.PrzydzialRozmiarow_ID
inner join Shops s with(nolock) on s.ID = p.Shop_ID
There is just outer joins to get correct data that I need to be displayed in gridview. And now when values p.FlagaWaznosci or p.Notatka is changed I want to save update in my database.
I try to use
//loads dataand fill to gridview
DataTable WszystkieProduktyDlaDanegoSklepu;
SqlDataAdapter sda555123 = new SqlDataAdapter("here is my select", conn123);
sda555123.Fill(WszystkieProduktyDlaDanegoSklepu);
//later update table Prooducts and save changed on p.Notatka and p.FlagaWaznosci
cmdbl = new SqlCommandBuilder(sda555123);
cmdbl.ConflictOption = ConflictOption.OverwriteChanges;
sda555123.Update(WszystkieProduktyDlaDanegoSklepu);
But this way I have error
So I searched a lot and found: I have to write own CommandUpdate.
So ... sda555123.UpdateCommand and I don't have idea how can I write own update for it in update command.
The update in SQL Server should looks like:
Update Products
set FlagaWaznosci = #Flagawaznosci from my sda555123,
Notatka = #Notatka from my sda555123
where id = # p.ID from my sda555123
How my command update should looks like here?
EDIT 1 :
i try added : WszystkieProduktyDlaDanegoSklepu.PrimaryKey = new DataColumn[] { WszystkieProduktyDlaDanegoSklepu.Columns["id"] }
but nothing . Still this error.
I would solve the problem by changing the approach instead of mutating the update command of the SqlDataAdapter.
Given that Products.id in your query is unique within the result set:
1- Create a temporary table (local or global), having its columns same as the result of the query with id as primary key.
2- Insert data into the temporary table using your select statement.
3- DataAdatper.selectQuery.commandText is set to "select * from TempTable"
4- The update command is now based on a simple select statement, consequently any change in the datagridview/datatable can be updated to the temptable using dataadapter.update(datatable)
5- As for the final database update, you could use the below statement
Update Prd
set Prd.FlagaWaznosci = TempTable.FlagaWaznosci ,Prd.Notatka = TempTable.Notatka etc.. all the fields that need to be updated
from my Products as Prd
Inner Join TempTable on TempTable.id = Prd.id
Note that the update in (5) will affect all rows, even unchanged ones.
To address this issue you can proceed as below
1- Save changed ids in a list.
List<string> lst = new List<string>();
foreach(DataRow dr in datatable.GetChanges(DataRowState.Modified))
{
lst.add(dr["id"].ToString());
}
2- Convert your list to a string value to be concatenated with the query in (5)
String strchange = String.Join(",",lst); //will give you id1,id2,...
//The update query becomes
Update Prd
set Prd.FlagaWaznosci = TempTable.FlagaWaznosci ,Prd.Notatka =
TempTable.Notatka etc.. all the fields that need to be updated
from my Products as Prd
Inner Join TempTable on TempTable.id = Prd.id
Where Prd.id In ( strchange )
Kindly update your tables separately because in join you just seen two or more than two tables into one table form . but you cant do any crud operation on

Retrieve data from different tables

I want to retrieve data from two tables like below. I have a Products table which has P_id, P_name columns and a BATCH table with p_id_fk as a foreign key to the Products table.
This is my query; I want to retrieved from product's name from the Product table because I have stored the Products table primary key as a foreign in the Batch table.
SqlDataAdapter sda = new SqlDataAdapter("Select batch_id, quantity, left_qty, purchaseDate, manufacturing_date, expiryDate from batch where Convert(DATE, expiryDate, 103) BETWEEN #from AND #to", con);
sda.SelectCommand.Parameters.AddWithValue("#from", Convert.ToDateTime(datePicker1.SelectedDate.Value).ToString("yyyyMMdd"));
sda.SelectCommand.Parameters.AddWithValue("#to", Convert.ToDateTime(datePicker2.SelectedDate.Value).ToString("yyyyMMdd"));
If you want to retrieve data from two tables you need to use a SQL JOIN
I am not sure of the exact make up of your tables but something like the below
Select batch_id,
product_name,
quantity,
left_qty,
purchaseDate,
manufacturing_date,
expiryDate
from batch B
INNER JOIN Products P
ON P.P_id = B.P_id
where Convert(DATE,expiryDate,103) BETWEEN #from AND #to
you need to have a join or cross apply here.
Option 1 - inner join:
Select
b.batch_id,pd.product_name,quantity,left_qty,
purchaseDate,manufacturing_date,expiryDate from batch b
inner join product pd on pd.p_id = b.p_id where Convert(DATE,expiryDate,103)
BETWEEN #from AND #to
Option 2 cross apply:
Select
b.batch_id,pd.product_name,quantity,left_qty,
purchaseDate,manufacturing_date,expiryDate from batch b
cross apply
(
select product_name from product p
where p.p_id = b.p_id
) pd
where Convert(DATE,expiryDate,103)
BETWEEN #from AND #to
for more about cross apply look here.
Not sure if I understood your question correctly, but I believe for your query you are looking for something simple as JOIN between Products and Batch tables:
SELECT
P.P_id,
P.P_name,
B.batch_id,
B.product_name,
B.quantity,
B.left_qty,
B.purchaseDate,
B.manufacturing_date,
B.expiryDate
FROM Batch AS B
INNER JOIN Products AS P
ON B.p_id_fk = P.P_id
WHERE CONVERT(DATE, B.expiryDate, 103) BETWEEN #from AND #to
p_id_fk name you provided might be not an actual column name in Batch table but rather the name of the foreign key constraint itself as it appears by the naming convention (_fk suffix).

Insert multiple records with values based on each other

Sorry for the bad title, I havent come up with a better one yet.
I am currently optimising a tool which basically does thousands of selects and inserts.
Assume the following relation
class A
{
public long ID; // This is an automatic key by the sqlserver
...Some other values
}
class B
{
public long RefID // Reference to A.ID;
... some other values...
}
class C
{
public long RefID // Reference to A.ID;
... some other values
}
What currently is happening is a SELECT to get ObjectA,
if it doesnt exist, create a new one. The Query returns the ID (OUTPUT INSERTED.ID)
Then it selects (inserts if not existant) the objects B and C.
Is there a way to compress this into a single SQL statement?
Im struggling at the part where the automatic generation of object A happens.
So it must do something like this:
IF NOT EXISTS(SELECT * FROM TableA WHERE someConditions)
INSERT... and get the ID
ELSE
REMEMBER THE ID?
IF NOT EXISTS(SELECT * FROM TableB WERE RefID = ourRememberedID)
INSERT...
IF NOT EXISTS(SELECT * FROM TableC WERE RefID = ourRememberedID)
INSERT...
Please note, stored procedures cannot be used.
A little help
You could issue these three in one statement
Use a DataReader NextResult
select ID from FROM TableA WHERE someConditions
select count(*) from TableB where refID = (select ID from FROM TableA WHERE someConditions)
select count(*) from TableC where refID = (select ID from FROM TableA WHERE someConditions)
But even then you take a risk the TableB or TableC had an insert before you got to it
If I could not use a stored procedure I think I would load the data into a #temp using a TVP
I think you could craft 4 statements in a transaction

How to get unique constraint names from SQL Server with C#

I have created a unique constraint in an SQL Server Database using the following statement:
ALTER TABLE mytable ADD CONSTRAINT mytable_unique UNIQUE (uid)
How can I get all unique constraint names programmatically with C# SQLConnection object?
query on information_schema.constraint_column_usage
SELECT TC.Constraint_Name ,
CC.Column_Name
FROM information_schema.table_constraints TC
INNER JOIN information_schema.constraint_column_usage CC
ON TC.Constraint_Name = CC.Constraint_Name
WHERE TC.constraint_type = 'Unique'
ORDER BY TC.Constraint_Name
You can also get these from sys.key_constraints:
select name from sys.key_constraints where type = 'UQ'

A Query Copy from 1 table into another + Values

I am trying to make this query work but i keep getting error.
insert into Table1 (CL1,CL2) Values ('TEST',CL2)
SELECT CL2 from Table2 where ID = 2
I am trying to take data from table 2 and put it in table 2 with the name TEST
Table1
is Empty
Table2
ID=2,SUP,SUP,SUP
if any one can help it would be great
insert into Table1 (CL1,CL2) SELECT 'TEST', CL2 from Table2 where ID = 2
Is this what you want:
INSERT INTO Table1 (CL1,CL2) VALUES ('TEST',(SELECT CL2 FROM Table2 WHERE ID=2))

Categories

Resources