entity-framework - 多种类型用户通知的数据模型

标签 entity-framework ef-code-first data-modeling

我想弄清楚如何建模通知。这是我尝试过的。

public class NotificationType
{
    public int NotificationTypeID { get; set; }
    public string Type { get; set; }
    public string Action { get; set; }
}

public class Notification
{
    public int NotificationID { get; set; }
    public bool ReadStatus { get; set; }
    public DateTime DateCreated { get; set; }
    [ForeignKey("User")]
    public int UserID { get; set; }
    [ForeignKey("NotificationType")]
    public int NotificationTypeID { get; set; }

    public int CommentID { get; set; }
    public int ProjectID { get; set; }

    public Comment Comment { get; set; }
    public Project Project { get; set; }
    public NotificationType NotificationType { get; set; }
    public User User { get; set; }
}

坦率地说,我觉得我仍然不知道我在做什么,但让我告诉你我想做什么,如果这是一个坏主意,告诉我,如果不是,请告诉我我是怎么做的。

我有 Notifications用于发生与 Comment 相关的操作, ReplyProject - 这就是我拥有所有这些导航属性和字段的原因。我想基本上使用NotificationType确定它是什么,然后使用适当的 ID 字段获取信息以向用户显示通知。

第一个问题,我似乎无法将这些 ID ( CommentID ProjectID ) 字段设为可空,因此我不必总是拥有它们。

如何使用数据注释和/或流畅的 api 或更好地设计我的模型使它们可以为空?

最佳答案

使它们可以为空的属性

public class Notification
{
    public int NotificationID { get; set; }
    public bool ReadStatus { get; set; }
    public DateTime DateCreated { get; set; }
    [ForeignKey("User")]
    public int UserID { get; set; }
    [ForeignKey("NotificationType")]
    public int NotificationTypeID { get; set; }

    public int? CommentID { get; set; }
    public int? ProjectID { get; set; }

    public Comment Comment { get; set; }
    public Project Project { get; set; }
    public NotificationType NotificationType { get; set; }
    public User User { get; set; }
}

然后使用流畅的API
modelBuilder.Entity<Notification>().HasOptional(n => n.Comment).WithMany()
    .HasForeignKey(n => n.CommentID);

关于entity-framework - 多种类型用户通知的数据模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14534119/

相关文章:

c# - Entity Framework 多重级联删除

c# - WCF 循环引用序列化和堆栈溢出错误

c# - 强制 Entity Framework 查询数据库

.net - 模型存储 edmx 文件不会在 Debug模式下生成,但会在 Release模式下生成

java - Elasticsearch 建模最佳实践

sql-server - Entity Framework 外键映射到同一个表

.net - Entity Framework Code First Migrations 认为有一个不应该存在的变化

time-series - 在 ArangoDB 中构建时间序列数据

c# - 什么是更好的设计/实践 : Nullable property or 1 value property and 1 bool "has" property?

c# linq 在 tph 中获取数据库中项目的类型