Nirman
Nirman

Reputation: 6793

Navigation properties are showing null randomly

Consider below as the table structure of my database. (Database: Geography)

Country >> CountryId, CountryName
City >> CityId, CityName, LanguageId
Language >> LanguageId, LanguageName

Following is a method in my WCF project (Project: Geography.WCFPortal)

[OperationContract]
public CountrySummary GetCountrySummary(string countryName)
{
CountrySummary countrySummaryRows = new CountrySummary();        
var result = from city in repository.GetQuery<City>()
                     .Include("Language")
                     .Where(city => city.Country.CountryName == countryName)
                     select city;

        countrySummaryRows.Country = this.GetCountry(countryName);

        foreach (var city in result.OrderByDescending(m => m.CityName).ToList())
        {
            countrySummaryRows.CityCollection.Add(city);
        }
        return countrySummaryRows;
}

Following is how CountrySummary class is defined: (Project: Geography.Contracts)

[Serializable]
[DataContract]
public class CountrySummary
{
public CountrySummary()
{
this.CityCollection = new List<City>();
}

[DataMember]
public List<City> CityCollection { get; set; }

[DataMember]
public Country Country { get; set; }

}

My MVC application is calling GetCountrySummary method.

One of my MVC view is showing list of Countries. There is a "View" link against each of them which calls the WCF method (GetCountrySummary) and displays it on another view.

The issue is that MVC randomly receives NULL in "Language" navigation property for some cities. Say, if I click "View" on India for first time, it works fine, and if I click it next time, it gives an error of "Object reference is null" and when I check my "CountrySummary" object, it is having Language NULL for some cities (but they are in the database).

Whenever I run this in WCF Test client, it always populates Currency. But it is failing at times while being called in MVC application.

Any idea of why this would be happening?

Upvotes: 0

Views: 168

Answers (1)

qujck
qujck

Reputation: 14578

My guess is that the repository instance is being reused due to it being initialised in the WCF start event. Try creating a new instance within the GetCountrySummary method to confirm.

see this post for more information

Upvotes: 1

Related Questions