seventyeightist
seventyeightist

Reputation: 135

Entity Framework - how to implement Tags (for Articles / Pages)

I'm writing a EF based website which will have many Articles (with id, author, date, title etc attributes) each of which is a member of a Category (10 possible categories each with id, title, associated icon etc)

Each article can also have several "tags". Like the question-tags that apply to SO questions.

For example Article ID 1 has:

Article ID 2 ("50 life hacks I discovered this year")

From the above there are 9 'distinct' tags of which 2016 and Lists apply to both articles and the others appear once each.

With a large number of articles there are an increasingly large number of tags.

Is this just a case of a many-to-many relationship of Article to Tag or is there some more natural/idiomatic way to represent that using EF?

The main things I want to do are:

I don't need to:

What I need to know:

My background is database so I understand about FKs and link tables etc, but am struggling on the EF side.

Note about my requirements: This is for a website I am creating for myself, so I already know the requirements. I won't have a situation where "the user" asks to be able to keep the ordering of the tags, for example.

Upvotes: 1

Views: 2832

Answers (1)

Kiarash Alinasab
Kiarash Alinasab

Reputation: 1013

You can add 2 Tables, Tag and TagRelation, Tag is responsible for saving TagNames such as #Test #AnotherTest, make sure there is no way to insert same tagName. In TagRelation you should keep the TagId (Fk of Tag table) and Guid (Fk of Article, Page and you name it). In this architecture every table needing Tag, must have a field with Guid type(uniqueidentifier in SQL data type) when you searching for ex. article you simply set inner join with TagRelation on Guid fields

public class Tag
{
    public long Id { get; set; }
    public string TagName { get; set; }
}

public class TagRelation
{
    public long Id { get; set; }
    public long TagId { get; set; }
    public Guid FkUniqueGuid { get; set; }

}

public class Article
{
    public long Id { get; set; }
    public Guid UniqueGuid { get; set; }
    //And another fields
}

Upvotes: 2

Related Questions