0

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!!!

user584018
  • 10,186
  • 15
  • 74
  • 160

1 Answers1

3

You should include State. Not StateId

public ZipCode GetByZip(string zip)
{
    using (GeoLibDbContext entityContext = new GeoLibDbContext())
    {
        return entityContext.ZipCodeSet.Include(e => e.State).FirstOrDefault(e => e.Zip == zip);
    }
}

Include works with navigation property, and in your case navigation property is State.

Kirill Bestemyanov
  • 11,946
  • 2
  • 24
  • 38