【问题标题】:Entity framework- EF Code First Select foreign key实体框架-EF Code First Select外键
【发布时间】:2017-07-02 08:33:34
【问题描述】:

型号:

public class Address
{
    [Key]
    public long AddressId { get; set; }

    public string Street { get; set; }

    public string Town { get; set; }

    public string State { get; set; }

    public string Country { get; set; }
}
public class User
{
    [Key]
    public long UserId { get; set; }

    public string UserName { get; set; }

    public string Password { get; set; }

    public virtual List<Address> Addresses { get; set; }
}

数据库上下文:

public class DataModelContext : DbContext
{
        public DbSet<Address> Addresses { get; set; }
        public DbSet<User> Users{ get; set; }
}

使用上面的代码为 DB 创建这个模式。

Addresses          Users
-----------        -------
AddressId(PK)      UserId(PK)
Street             UserName 
Town               Password 
State  
Country 
User_UserId(FK)

现在我想从 Addresses 表中访问 User_UserId,但它没有在那里显示任何属性。它给出的错误“地址不包含 User_UserId 的定义.....

using (var db = new DataModelContext())
{
       db.Addresses.Select(x=>x.User_UserId).ToList();
}

【问题讨论】:

    标签: entity-framework entity-framework-4 entity-framework-6 entity-framework-5 asp.net-mvc-5.2


    【解决方案1】:

    在创建模型时使用外键关联而不是独立关联。这意味着,您必须在模型中包含外键属性以及相应的导航属性。例如:

    public class Address
    {
        ...
        public int UserId {get; set;} //Foreign-Key property
    
        [ForeignKey("UserId")]
        public virtual User User { get; set; } // Navigational Property  
        ...
    }
    

    阅读this article了解更多信息。

    【讨论】:

      猜你喜欢
      • 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
      相关资源
      最近更新 更多