title: "unable to create a null constant value of type 'anonymous type'" for nullable column in db
body: <p>I'm using EF and MVC to access data in a SQL database and am wishing the controllers to communicate using json (using REST from Android so not using the Views).  </p>
  
  <p>I found it necessary to change the controllers to project the data via anonymous objects to avoid a circular reference problem between the main and reference tables, however this has now lead to a new problem when trying to create the json for a collection of objects, when the underlying record(s) contains null in an optional foreign key field.</p>
  
  <p>Table User has (for the sake of example) two foreign keys to code/description tables Language and Country, Language is mandatory and Country is optional.</p>
  
  <p>I found I could successfully replace the Country element with null by testing for the null id., the json comes out fine...</p>
  
  <pre><code>{
  "UserID": 3,
  "UpdatedWhen": null,
  "Country": null,
  "Language": {
      "LanguageID": 1,
      "LocalName": "English"
      }
  }
  </code></pre>
  
  <p>...but have now discovered that this doesn't work when I have multiple User objects to deal with.</p>
  
  <pre><code>    public JsonResult Index()
      {
          var users = from user in db.Users
                      select new
                      {   user.UserID,
                          &lt; snip &gt;
                          user.CreatedWhen,
                          user.UpdatedBy,
                          user.UpdatedWhen,
                          Country = (user.Country == null ? null : new { user.Country.CountryID, user.Country.LocalName }),
                          Language = new { user.Language.LanguageID, user.Language.LocalName } };
  
          return Json(users.ToList(), JsonRequestBehavior.AllowGet);
      }
  </code></pre>
  
  <p>From what I've read the problem is with my .ToList(), it doesn't like the null Country object, because if I deal with just a single user e.g.</p>
  
  <pre><code>    private object projectUser(User user)
      {
          return new
          {
              user.UserID,
              &lt; snip &gt;
              user.UpdatedWhen,
              Country = (user.Country == null ? null : new { user.Country.CountryID, user.Country.LocalName }),
              Language = new { user.Language.LanguageID, user.Language.LocalName } };
  </code></pre>
  
  <p>...it works just fine.</p>
  
  <p>I've hunted about but simply cannot find a similar enough example of how to better do this, could anyone please suggest a way.</p>
  
  <p>Thanks in advance.</p>