I am getting below error while trying to access below method,
public ZipCode GetByZip(string zip)
{
using (GeoLibDbContext entityContext = new GeoLibDbContext())
{
return entityContext.ZipCodeSet.Include(e => e.StateId).FirstOrDefault(e => e.Zip == zip);
}
}
Below are the POCO and db context classes,
public class State
{
public int StateId { get; set; }
public string Name { get; set; }
}
public class ZipCode
{
public int ZipCodeId { get; set; }
public string City { get; set; }
public int StateId { get; set; }
public string Zip { get; set; }
public string County { get; set; }
public State State { get; set; }
}
public class HelloLibDbContext : DbContext
{
public HelloLibDbContext()
: base("name=HelloLibDbContext")
{
Database.SetInitializer<HelloLibDbContext>(null);
}
public DbSet<ZipCode> ZipCodeSet { get; set; }
public DbSet<State> StateSet { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
modelBuilder.Entity<ZipCode>().HasKey<int>(e => e.ZipCodeId)
.HasRequired(e => e.State).WithMany().HasForeignKey(e => e.StateId);
modelBuilder.Entity<State>().HasKey<int>(e => e.StateId);
}
}
If I removed ".Include(e => e.StateId)", then I m getting any error, but at the same time "State" property is null, which defines in "ZipCode" class.
What could be the reason? Please suggest!!!