我在尝试访问以下方法时遇到错误,
public ZipCode GetByZip(string zip)
{
using (GeoLibDbContext entityContext = new GeoLibDbContext())
{
return entityContext.ZipCodeSet.Include(e => e.StateId).FirstOrDefault(e => e.Zip == zip);
}
}
下面是POCO和db上下文类,
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);
}
}
如果我删除了“.Include(e =&gt; e.StateId)”,那么我得到任何错误,但同时“State”属性为null,它在“ZipCode”类中定义。
可能是什么原因?请建议!!!
答案 0 :(得分:2)
您应该加入State
。不是StateId
public ZipCode GetByZip(string zip)
{
using (GeoLibDbContext entityContext = new GeoLibDbContext())
{
return entityContext.ZipCodeSet.Include(e => e.State).FirstOrDefault(e => e.Zip == zip);
}
}
包括使用导航属性,在您的情况下导航属性为State
。