williamsandonz
williamsandonz

Reputation: 16420

ASP.NET MVC Entity framework how to structure this code

I have a few structures: User, Item, FavouriteItem.

User has many items, and can have many faourite items (which just link to items).

I've got the decision of either creating a model: "FavouriteItem" and give a user a list of these, or, store the favourite item ids in a column on the user table. i.e favourite_items: "1,2,5,9".

The latter seems like it will be a lot faster if the user base grows, but then I have the pain of having to split the string, create an array e.t.c, it's a bit more painful.

What is the recommended choice to make here? I've already done the earlier option and love its flexibility/ease-of-use, but a bit worried about its scalability.

Upvotes: 0

Views: 111

Answers (3)

James
James

Reputation: 82096

In terms of speed, it might be more effecient to store the FavouriteItems in the User table if you expect your table to be storing huge amounts of data. However, if you want a clean, structured database then I would introduce a foreign key table UserItems with a Favourite column e.g.

UserItems
---------        
UserId           
ItemId
Favourite

You can always optimize your query if you start to hit bottlenecks.

Upvotes: 1

Eric J.
Eric J.

Reputation: 150108

The best choice depends to some extend on the query patterns you will experience in your application. I'm going to assume that Items are specific to a User and not shared between users. Based on what you are saying, I would go with a structure something like:

public class User
{
    public IList<Item> Items { get; set; }
    public IEnumerable<Item> FavoriteItems
    {
        get
        {
            return from i in Items where i.IsFavorite select i;
        }
    }
}

public class Item
{
    public bool IsFavorite { get; set; }
}

That will work well if the list of items per user is not huge, even if you have many users and many items.

Upvotes: 1

Dave Hogan
Dave Hogan

Reputation: 3221

How about User, Item, UserItem (link table which has a IsFavouriteItem bit field. So UserId, ItemId, IsFavouriteItem as the columns)?

Upvotes: 3

Related Questions