I am working a project that uses entity framework. I want simple thing when people click to searchLookUpedit
button I want to show values filtered according to Companies that exists in Orders. So here is the code:
private void SearchLookUpEdit_Customer_Click(object sender, EventArgs e)
{
object [] siparisNo = new object[gridView1.RowCount];
List<Siparisler> siparisList = new List<Siparisler>();
List<int> firmaIds = new List<int>();
for (int i = 0; i < gridView1.RowCount; i++)
{
siparisNo[i] = gridView1.GetRowCellValue(i,"SiparisNo");
int sipNo = Convert.ToInt32(siparisNo[i]);
Siparisler siparis = context.Siparisler.Where(p => p.Id == sipNo).FirstOrDefault();
siparisList.Add(siparis);
firmaIds.Add(siparis.Firma_Id);
}
for (int i = 0; i < firmaIds.Count; i++)
{
int a = firmaIds[i];
firmalarBindingSource.DataSource = context.Firmalar.Where(p => p.Id == );
}
}
In here second for loop . Lets imagine that in firmaIds<int>
list type have 3 values. And assume that they are 3, 5 and 8 for example, and I want only this 3 Companies will exist in firmalarBindingSource.DataSource
after the click event finished running. I tried but it did not. If my criteria were different data type it was easy to filter. Is there anyway to do this?
If I have understood what you are asking try replacing
for (int i = 0; i < firmaIds.Count; i++)
{
int a = firmaIds[i];
firmalarBindingSource.DataSource = context.Firmalar.Where(p => p.Id == );
}
with
firmalarBindingSource.DataSource = context.Firmalar.Where(p => firmaIds.Contains(p.Id));
@Faby answered your question, but I just wanted to add that you can also optimize the first part of your code, so you could do everything in two lines of code in a more functional manner using Linq
:
IEnumerable<Firmalar> firmalarDataSource = Enumerable.Range(0, gridView1.RowCount - 1)
.Select((index) =>
{
var siparisId = Convert.ToInt32(gridView1.GetRowCellValue(index, "SiparisNo"));
var siparis = context.Siparisler.FirstOrDefault(p => p.Id == siparisId);
return context.Firmalar.FirstOrDefault(f => f.Id == siparis.Firma_Id);
})
.Distinct();
firmalarBindingSource.DataSource = firmalarDataSource;
Note: these are two lines, but i adjusted the formatting to be more readable ;)
If you value performance over lines of code, here is a three line example with less roundtrips to the DB:
var siparisIds = Enumerable.Range(0, gridView1.RowCount - 1)
.Select(index => Convert.ToInt32(gridView1.GetRowCellValue(index, "SiparisNo")));
var firmaIds = context.Siparisler.Where(p => siparisIds.Contains(p.Id)).Select(s => s.Firma_Id).Distinct();
firmalarBindingSource.DataSource = context.Firmalar.Where(f => firmaIds.Contains(f.Id));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With