型号:
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();
}
答案 0 :(得分:1)
创建模型时,使用外键关联代替独立关联。这意味着,您必须在模型中包含外键属性以及相应的导航属性。例如:
public class Address
{
...
public int UserId {get; set;} //Foreign-Key property
[ForeignKey("UserId")]
public virtual User User { get; set; } // Navigational Property
...
}
阅读this article了解详情。