I have a ListView which I filled in from SQL Server view called view_ListaKlientow with this query:
private void fillClientsList() {
using (var context = new EntityBazaCRM()) {
var listaKlientow = from d in context.view_ListaKlientow
select d;
objectListViewListaKlientow.SetObjects(listaKlientow.ToList());
objectListViewListaKlientow.AutoResizeColumns();
}
}
Then after user double clicks one row in ListView, I read ID from the view_ListaKlientow and use fillClientGui to fill necessary fields in gui (for a test only one field is included).
private void objectListViewListaKlientow_DoubleClick(object sender, EventArgs e) {
foreach (view_ListaKlientow user in objectListViewListaKlientow.SelectedObjects) {
int id = user.KlienciID;
fillClientGui(id);
TabPageActivate(tabControlMain, tabPageKlient);
}
}
private void fillClientGui(int klientId) {
using (var context = new EntityBazaCRM()) {
IQueryable<Klienci> klient = context.Kliencis.Include("Podmioty").Where(d => d.KlienciID == klientId);
foreach (var source in klient.ToList()) {
textNIP.Text = source.Podmioty.PodmiotNIP;
}
}
}
Now I’m wondering since I know exactly I’m querying for one ID i should be getting only particular client and not a list of clients so foreach from fillClientGui just to travers IQueryable<Klienci> seems like additional unnecessary code. Or this is how it should be done? I’m trying to learn Entity and some things aren’t just clear to me yet 🙂
If you’re sure that you’ve got only one instance to be returned form the database, you can use the extension function
FirstOrDefault()in this case: