tuta4
tuta4

Reputation: 79

EF code first and virtual properties

I have two tables Articles and Events and I'd like to provide a commenting functionality to the users on both types. The hard part is that I'd like to use a navigation property that returns the comments belonging to the given EF object.

public class Article
{
    public virtual ICollection<Comment> Comments { get; set; }
    /* more properties here */
}

public class Event
{
    public virtual ICollection<Comment> Comments { get; set; }
    /* more properties here */
}

public class Comment
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int CommentId { get; set; }
    public string Msg { get; set; }
    public DateTime SentAt { get; set; }

    public int TargetId { get; set; }
    public CommentTargeType TargetType { get; set; }
}

public enum CommentTargeType
{
    Article,
    Event
}

As you see the TargetId would be the id of the Article or of the Event and the TargetType is to distinguish these two types. So, is there any way to do this? Or would it be better to create an ArticleComments and an EventComments type instead?

Upvotes: 0

Views: 410

Answers (1)

Ameen
Ameen

Reputation: 2586

Your current design is essentially using the same field in your object to be a foreign key into 2 tables. I would advise against that because the database won't be able to force any constraints or do integrity checks.

You can add two int? fields, one called ArticleId and one called EventId to accomplish what you want. Since the types are int? they will be nullable fields in the database.

I would even go one step farther and use the ForeignKey attribute so that EntityFramework knows about this and creates the foreign keys for you.

[ForeignKey("Article")]
public int? ArticleId { ... }
public virtual Article Article { get; set; }

[ForeignKey("Event")]
public int? EventId { get; set; }
public virtual Event Event { get; set; }

Upvotes: 1

Related Questions