Xaxum
Xaxum

Reputation: 3675

Creating multiple tables in one model ASP.Net MVC 4

I have a Person model which represents different aspects of a person. In my person model I have the following:

public class PersonsContext : DbContext
    {
        public PersonsContext()
            : base("SiteDBCon")
        {
        }

        public DbSet<Person> Persons { get; set; }

        public DbSet<UserProfile> UserProfiles { get; set; }
    }

    public class Person
    {
        public int ID { get; set; }
        public int Age { get; set; }
        public string Gender { get; set; }
        public string Race { get; set; }
        public string Ethnicity { get; set; }
        public int UserId { get; set; }                //User who input data
        public UserProfile UserProfile { get; set; }   //User who input data

    }

However, there are some things that a person can have multiple entries for, address - current previous, Phone numbers current previous etc.. All of which I want in separate tables. Can I add those tables in the PersonModel or do I need to create a new Model for each table, eg. AddressModel, PhoneModel? They will all have a one to many relationship with the Person table. If you can do it is it a good idea to have all in one Model. In the past I have created separate models but I am questioning if that is necessary.

Upvotes: 0

Views: 2910

Answers (1)

Jerad Rose
Jerad Rose

Reputation: 15513

What you are referring to is database normalization. Generally speaking, you want to normalize your data anytime you see a many-to-one or many-to-many relationship in your models.

The main question is, will a person always have exactly one address/phone? If so, it may make sense to keep them with your Person model. If they may (now or, in the future) have multiple addresses/phones, then it's almost always best to normalize these out into different models.

Even if you don't need multiple addresses/phones now, you may need to at some point, and for this reason, most people will opt to normalize related like this out.

Another benefit is that this will allow you to have types assigned to your addresses (shipping/billing) and phone (cell/home/work).

If I were you, I would consider setting up an Address and Phone model, and have them as one-to-many relationships to your Person via a List<> (or other IEnumerable<>).

Upvotes: 1

Related Questions