0

I'm learning Entity Framework and decided to re-implement a knowledge base application which I had written using ADO.NET a few years back.

I have three entities: Article, UserAccount and Rating.

Article and UserAccount are pretty self-explanatory. Rating is a table containing possible ratings: very good = 5, good = 4, average = 3, poor = 2 and very poor = 1.

When viewing articles I want to display the average rating for that article. If a user has already providing a rating on that article - they shouldn't be allowed to rate on it again.

I've managed to successfully create Lookup tables between two entities using fluent API, using something similar to:

        HasMany(a => a.Tags)
            .WithMany(t => t.Articles)
            .Map(x =>
                {
                    x.ToTable("ArticleTags");
                    x.MapLeftKey("ArticleId");
                    x.MapRightKey("TagId");
                });

I am struggling to create or even attempt start creating the lookup table between three tables:

ArticleUserRatings (ArticleId, UserAccountId, RatingId)

I could create an entity called ArticleUserRating

public class ArticleUserRating
{
    public int ArticleId { get; set; }
    public int UserAccountId { get; set; }
    public int RatingId { get; set; }
}

but this doesn't sit comfortable with me, its a entity for the sake of this relationship type.

Is there a way to define this relationship without creating the entity?

Any guidance will be much appreciated.

  • I really don't think that it is possible in entity framework let alone code first. Whenever I am creating such joins I generally have a junction table in the middle and an entity which corresponds to that. One way to look at it is "Can it be done in the designer?" I don't think so which probably means not in code first. One thing though... what is the relating between article and user? – Dave Williams Jun 28 '13 at 15:44
  • In relation ratings - the three keys define a users rating on a particular article. There are other relationships between such as article creator and article approver etc but these aren't related to my query above. Thanks for the feedback. – user1244893 Jun 28 '13 at 16:26
  • Would it not be better to have just one user per rating so a 1:N between Users and Ratings and then a junction only for ArticleRatings. That way you can have `Article.Ratings.Where(rating => rating.User == CurrentUser).Any()` to check for previous ratings but you don't need a huge 3 way junction? – Dave Williams Jun 28 '13 at 16:33
  • Thanks Dave, took your advice. I've made Rating an enum instead and just have a junction table between Users and Ratings. – user1244893 Jul 01 '13 at 13:56

0 Answers0