Issue with combobox when I bind using linq join query - c#

I am binding ComboBox using LINQ Join query. Below is my code:
var list = (from a in context.tbl_Products
join c in context.tbl_CurrentStock on a.ProductID equals c.ProductID
where c.Qty > 0
select new
{
ProductID = a.ProductID,
ProductName = a.ProductName
}).ToList();
cmbProduct.DataSource = list;
cmbProduct.ValueMember = "ProductID";
cmbProduct.DisplayMember = "ProductName";
cmbProduct.SelectedIndex = -1;
Table Details:
tbl_Products : ProductID, Product Name
Data in table
1,ABC
2,BCA
3,CDA
tbl_CurrentStock: StockID,ProductID,Qty
Data in table:
1,1,5
2,2,10
3,3,50
I am using cmbProduct.SelectedValue like below:
int ProductID = Convert.ToInt32(cmbProduct.SelectedValue);
var Product = context.tbl_Products.Single(o => o.ProductID == ProductID);
Until here it is fine. In combobox I have selected "ABC", but I am getting cmbProduct.selectedvalue value as 2 instead of 1. Same way if I select 2nd product getting value as 3 instead of 2, it is not giving selected value, instead it is giving first value in the list. What could be the problem? It's silly and eating my head. This is working fine, when I don't use JOIN Query (if I bind data from only one table)
Thanks in Advance

Problem resolved after changing sorted property of combobox to false. Combobox is sorting the productnames but not product IDs. This was causing issue. –

Related

C# Linq to Entity Framework multiple unrelated queries

I have a situation where I need data from multiple database tables.
Table 1 - has list of columns which needs to be displayed on front end html, angular kendo grid - which is configurable from separate Admin configuration.
Table 2 (joining of some other tables)- has the data which needs to be displayed on the angular front end.
My linq here which I am using currently is as below.
Query 1: to get list of columns to be displayed on Grid
var columns = from cols in _context.columns
select cols.colNames;
Query 2: Get the actual data for list
var data = from cust in _context.customer
join details in _context.custDetails on cust.id equals details.custid
join o in _context.orders on cust.id equals o.custid
where cust.id == XXXX
select new Customer
{
Id = cust.Id,
Name = cust.Name,
Address = details.Address,
City = details.City,
State = details.State,
OrderDate = o.OrderDate,
Amount = o.Amount
//15 other properties similarly
};
returns IQueryable type to Kendo DataSourceRequest
Currently, From my ui I have been make two api calls one for columns and one for getting the actual data, and show/hide the columns which are configured in the columns table.
But the problem is if anyone looks at the api calls on the network or on browser tools they could see the data being returned for the columns that are to be hidden which is a security problem.
I am looking for a single query for my api which returns the data using second query which should be smart enough to send the data only for configured columns (there could be 30 different columns) and set the other properties to null or doesn't select them at all. there are some properties which needs to be returned always as they are being used for some other purpose.
I searched many resources on how could I generate dynamic linq select using the configured columns.
Please some one help me in resolving this problem
you can do something like this. Assuming you columns tables a Boolean column Display and when it is true Column will be displayed and when it is false it wont be displayed.
var columns = (from cols in _context.columns
select cols).ToList(); // note I am getting everything not just column names here...
var data = from cust in _context.customer
join details in _context.custDetails on cust.id equals details.custid
join o in _context.orders on cust.id equals o.custid
where cust.id == XXXX
select new Customer
{
Id = cust.Id,
Name = cust.Name,
Address = details.Address,
City = details.City,
State = details.State,
OrderDate = o.OrderDate,
Amount = o.Amount
//15 other properties similarly
}.ToList();
var fileterdData = from d in data
select new Customer
{
Id = DisplayColumn("ID",columns)? cust.Id:null,
Name = DisplayColumn("Name",columns)? cust.Name:null,
Address = DisplayColumn("Address",columns)? details.Address:null,
// do similarly for all other columns
}.AsQueryable(); // returns IQueryable<Customer>
private bool DisplayColumnn(string columnName,List<Columns> cols)
{
return cols.Where(x=>x.ColumnName==columnName).First().Display();
}
So now you will have this code as part of one web API call which is going to do two SQL calls one to get columns and other to get data then you will use Linq To Entity filter columns which you dont want ( or want them to null). return this filtered data back to UI.

Selecting Specific Child Records In Linq TO SQL C#

I have a table say Category with the following fields:
cat_id, cat_name and Cat_desc
I also have another table product with the following fields:
pro_id, cat_id, pro_name and pro_desc, is_finished
Ordinarily, if I select a category with Linq to sql, it returns the category with all the associated products.
But I want to select a category but the products returned should be only product with is_finished value that is true.
any suggestion/code sample will be appreciated.
You need to join the tables:
select * from product p
left join Category c on c.cat_id = p.cat_id
where c.cat_name = 'yourcategory' and p.is_finished = 1
In linq to SQL:
var query = from product in products
join category in categories on category.cat_id = product.cat_id
select new { product.is_finished = true, category.cat_name = "yourcategory" };
This is probably the wisest way to do what you're asking:
var query = from product in products
select new {
product,
finishedCategories = product.categories.Where(c => c.is_finished)
};
This creates an anonymous type that has the data you're looking for. Note that if you access .product.categories you'll still get all of that product's categories (lazily-loaded). But if you use .finishedCategories you'll just get the categories that were finished.

Linq how to move all values of two columns to another table

I want to move 2 columns of my table to an another table. I can select values that i want to move but i'am unable to move them. How can i make this ? Here is my implementation
var cartQuery = (from c in db.CartTbls.AsQueryable()
join cs in db.CartShoeTbls on c.CartID equals cs.CartID
where c.CustomerID == cusID
select new {c.CustomerID,c.TotalPrice,cs.ShoeID,cs.Quantity});
What i want to do is copy the all values of ShoeID and Quantity attiributes. Any help would be appriciated.
Use should add the selection to the table and save the changes:
foreach (var item in cartQuery)
db.OrderShoeTbl.Add(new OrderShoe()
{ ShoeID = item.ShoeID, Quantity = item.Quantity });
db.SaveChanges();
if you are using Linq to SQL, the insert is different and should look like this:
foreach (var item in cartQuery)
db.OrderShoeTbl.InsertOnSubmit(new OrderShoe()
{ ShoeID = item.ShoeID, Quantity = item.Quantity });
db.SubmitChanges();
Stefan's answer is OK however you may insert everything in one step:
var cartQuery = (from c in db.CartTbls.AsQueryable()
join cs in db.CartShoeTbls on c.CartID equals cs.CartID
where c.CustomerID == cusID
select new OrderShoeTbl{ShoeID = c.ShoeID, Quantity = c.Quantity});
db.OrderShoeTbl.InsertAllOnSubmit(cartQuery);
db.SubmitChanges();
EDIT
If you want to delete data from source table I would also wrap everything in single transaction to avoid inconsistency in case of errors.

How to get a column value from data table with Linq

How to get a column value from a data table object. I have the id column on which basis I am trying to get another column value.
e.g. ApplicationId is the primary key column which I have and now I want to get the xyz column value for this ApplicationId.
I have accomplished my result by making use of the following Linq statement
List<string> lstResult= (from table in dt.AsEnumerable()
where table.Field<int>("Id") == id
select table.Field<string>("status")).ToList();
string dtStatus = lstResult[0];
you can do it lik this
var results = (from rows in dt.AsEnumerable() select new {resultcolumnname=row["resultcolumnname"]}).where(item=>item.columnname == value).ToList()
var x= from myrow in myDataTable.asEnumerable() where myrow.ApplicationId==[YourValue] select myRow.[ColumnYouWant];
I am not great when it comes to linq but this should do the trick.

Data grid View ( winform ) not populating properly

I have two tables in my database Department and Faculty . I am populating a datagridview for department list in my winform application . Both of my tables are following
Department
Sno (int)
Name (varchar(max))
Status (bit)
Faculty_id (int)
Faculty
Sno (int)
Name
Status
Now come to code i simply drag and drop a datagridview into my form and go to code behind file . In my form's load method i write following code
var main = new SRMEntities();
var departs = main.Department.ToList();
DepartmentGrid.DataSource = departs;
now when my form load it show like this
Look in faculty column its showing nothing and when we create department we store a faculty id into department . i want to show faculty name here .
Please let me know if you have any question .
Thanks in advance
Edit
My Database Diagram
Here is correct join:
var main = new SRMEntities();
var query = from f in main.Faculty
join d in main.Department on f.Sno equals d.Faculty.Sno
select new { d.Sno, d.Name, d.Status, Faculty = f.Name };
DepartmentGrid.DataSource = query.ToList();
Everything is dependent on your query............ Your query should contain both the tables with Join.
var main = new SRMEntities();
var departs = main.Department.ToList();
DepartmentGrid.DataSource = departs;
Please check the above code "main.Department.ToList();" is returning only Departments and your assigning the "departs" to your grid.
Whether "main.Department" contains the "Faculty" table info?
By looking at your code i am guessing you have a seperate items like below
1.main.Department
2.main.Faculty
You need to join your tables
something like:
var main = new SRMEntities();
var source = (from d in main.Department
join f in main.Faculty on d.Faculty.Sno=f.Sno
select new
{
Sno = d.Sno ,
Name = d.Name,
Status = d.Status,
Faculty = f.Name
}
);
DepartmentGrid.DataSource = source.ToList();
Regards

Categories

Resources