Entity framework- EF Code First Select foreign key

asp.net-mvc-5.2 entity-framework entity-framework-4 entity-framework-5 entity-framework-6

Question

Model:

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

This database schema is being created using the code above.

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

I'm trying to retrieve User UserId from the Addresses database, but no properties are appearing. Address does not have a definition for User UserId, according to the error message.

using (var db = new DataModelContext())
{
       db.Addresses.Select(x=>x.User_UserId).ToList();
}
1
0
2/14/2017 6:48:34 AM

Accepted Answer

When building models, use International Key Association rather than unrelated organisation. This requires that you provide a foreign key property and a matching navigational property in your model. For instance:

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

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

Check out this piece for additional details.

1
2/14/2017 7:07:11 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow