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

Using above code its creating this schema for DB.

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

Now i want to access User_UserId from Addresses table, but it not showing any property there. Its giving error "Address does not contain a definition for User_UserId.....

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

Accepted Answer

Use Foreign-Key Association instead of independant association while creating models. It means that, you must include a foreign key property in your model alongside with a corresponding Navigational Property. For example:

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

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

Read this article for more information.

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