【问题标题】:The EntityType does not declare a navigation property with the name 'StateId' [duplicate]EntityType 未声明名为“StateId”的导航属性 [重复]
【发布时间】:2015-09-27 13:54:06
【问题描述】:

我在尝试访问以下方法时遇到错误,

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 => e.StateId)”,那么我会收到任何错误,但同时“State”属性为空,它在“ZipCode”类中定义。

可能是什么原因?请推荐!!!

【问题讨论】:

    标签: entity-framework


    【解决方案1】:

    您应该包含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

    【讨论】:

    • 如果属性是枚举而不是导航属性,也会发生这种情况。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多