locked
Retrieve only StateCode via LINQ RRS feed

  • Question

  • I've written the following LINQ query that is attempting to return the StateCode values for all Contact records that match a particular last name

    var cs = (from c in myCTX.ContactSet
              where c.LastName == "Smith"
              select new Contact
              {
                  StateCode = c.StateCode
              });
    foreach (Contact c in cs)
    {                                       
    }

    However, I'm receiving the following error in my code on the StateCode = c.StateCode line:

    Property or indexer 'StateCode' cannot be assigned to -- it is read only

    Any idea how I can get around this error? 

    Thank you

    Tuesday, March 25, 2014 9:07 PM

Answers

  • Hi,

    Yes, this is a known issue for LINQ projections like this for read only fields. You'll need to project onto an anonymous type to get the StateCode:

    var cs = (from c in myCTX.ContactSet
              where c.LastName == "Smith"
              select new
              {
                  StateCode = c.StateCode
              });

    Hope this helps,

    Scott


    Scott Durow
    Blog www.develop1.net    Follow Me
    Rockstar365
    If this post answers your question, please click "Mark As Answer" on the post and "Mark as Helpful"

    • Marked as answer by Cipher Tuesday, April 8, 2014 1:55 PM
    Tuesday, March 25, 2014 9:37 PM
    Answerer