简体   繁体   English

EF代码优先和虚拟属性

[英]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. 我有两个表格ArticlesEvents ,我想为两种类型的用户提供评论功能。 The hard part is that I'd like to use a navigation property that returns the comments belonging to the given EF object. 困难的部分是我想使用导航属性,该属性返回属于给定EF对象的注释。

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. 如您所见, TargetId将是ArticleEvent的ID,而TargetType是区分这两种类型。 So, is there any way to do this? 那么,有什么办法可以做到这一点? Or would it be better to create an ArticleComments and an EventComments type instead? 还是最好改为创建ArticleComments和EventComments类型?

Your current design is essentially using the same field in your object to be a foreign key into 2 tables. 您当前的设计实质上是使用对象中的相同字段作为2个表中的外键。 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? 您可以添加两个int? fields, one called ArticleId and one called EventId to accomplish what you want. 字段,一个称为ArticleId,一个称为EventId,以完成所需的操作。 Since the types are int? 既然类型是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属性,以便EntityFramework知道这一点并为您创建外键。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM