nikhilthecoder
nikhilthecoder

Reputation: 299

ASP MVC 4 Mapping one to one relationship code first

I am new to ASP MVC and am working on a project with complex related data model. so while working on the relationships i looked online and got the following example on the Blog of asps.net :

namespace CodeFirst.Associations.OneToOneFK
{
    public class User
    {
        public int UserId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }        
        public int BillingAddressId { get; set; }
        public int DeliveryAddressId { get; set; }       

        public Address BillingAddress { get; set; }
        public Address DeliveryAddress { get; set; }
    }

    public class Address
    {
        public int AddressId { get; set; }
        public string Street { get; set; }
        public string City { get; set; }
        public string PostalCode { get; set; }   
    }
}

So my doubt is do we really need both the int BillingAddressID as well as Address BillingAddress? Also, how do we associate an address to a user if we don't use AddressID.

Thanks for the help. :)

Upvotes: 1

Views: 1430

Answers (1)

devdigital
devdigital

Reputation: 34349

int BillingAddressID is called a foreign key property.

BillingAddress is called a navigation property (in this case a reference navigation property).

Foreign key properties aren't required to define a relationship, but they do simplify certain coding patterns. The general recommendation is to use both navigation properties and foreign key properties.

See here for more information about why FK associations were introduced.

Upvotes: 2

Related Questions