none
dynamic combox data source from EF - can the Linq query be improved? RRS feed

  • General discussion

  • I still learning Linq and Entity Framework.

    I have a comboxbox depending on another. I manged to get the 2nd dependent combobox working but is there a better way?

    here is ny code

    myApp.Entities1 contextEF = new myApp.Entities1(
      "MetaData=res://*/;"+
      myApp.Properties.Settings.Default.ConString);
    AcctGrpCbx.DataSource = contextEF .AcctGroup;
    AcctGrpCbx.DisplayMember = "acct_grp";
    AcctGrpCbx.ValueMember = "Acct_grp_ID";
    int acctGrpID = int.Parse(AcctGrpCbx.SelectedValue.ToString());
    var masterClientID = from a in contextEF .AcctGroup
     where a.Acct_grp_ID.CompareTo(acctGrpID) == 0
     select a.Master_Client_ID;
    // so far so good	
    int mc = 0;
    foreach int acctGrpID = int.Parse(AcctGrpCbx.SelectedValue.ToString());
       var aGrp = from a in ieFinExecContext.AcctGroup
          where a.Acct_grp_ID==acctGrpID
          select a;
       int mcID = 0;
       var aMClientIDs = from a in ieFinExecContext.AcctGroup
            where a.Acct_grp_ID==acctGrpID
            select a.Master_Client_ID;
       foreach (int i in aMClientIDs) { mcID = i; break;} // take the first one(actully first and only one)
       var clients = from c in ieFinExecContext.CLIENT
           where c.Master_Client_ID == mcID
           select c;
       
       clientCbx.DisplayMember = "Client_alias";
       clientCbx.ValueMember = "Client_ID";
       clientCbx.DataSource = clients;
       clientCbx.Show();

    Although I do have Using System.Linq, I just don't seem to be able to use FirstOrDefault.  COnsequently I use the foreach Kliuge above.

    Also, is it true that I can only use simple Linq not nested query? 



    • Edited by fs - ab Wednesday, April 4, 2012 1:07 AM
    Tuesday, April 3, 2012 6:55 AM

All replies

  •  int aMClientIDs = (from a in ieFinExecContext.AcctGroup
            where a.Acct_grp_ID==acctGrpID
            select a.Master_Client_ID).Single();

    Please refer to the code above, you needn't to use foreach, you only queried out an ID which is int type.

    Fighting like Allen Iverson. Neve give up!

    Friday, April 6, 2012 2:12 AM