0

型号:实体框架 - EF代码优先选择外键

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; } 
} 

的DbContext:

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) 

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

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

回答

1

使用外键关联,而不是独立的协会在创建模式。这意味着,你必须包括外国在模型旁边有一个相应的导航性能的主要特性,例如:。

public class Address 
{ 
    ... 
    public int UserId {get; set;} //Foreign-Key property 

    [ForeignKey("UserId")] 
    public virtual User User { get; set; } // Navigational Property 
    ... 
} 

阅读this article了解更多信息