Entity Framework 必填 可选

Entity Framework Required With Optional

我有以下模型,我试图使 Request 对象上的 Notification 属性 为空或通知的 ID。

但是,我不太确定如何使用流畅的映射来映射它。 HasOptional -> WithMany 似乎是我能得到的最接近的,但我想确保 Requests 中的 NotificationId 列是唯一的。使用流畅的映射实现此目的的最佳方法是什么?

public class Request
{
    public int RequestId { get; set; }
    public string Description { get; set; }
    public int? NotificationId { get; set; }
    public virtual Notification Notification { get; set; }
}

public class Notification
{
    public int NotificationId { get; set; }
    public string Description { get; set; }
    public DateTime CreateDate { get; set; }
}

public class RequestMap : EntityTypeConfiguration<Request>
{
    public RequestMap()
    {
        HasKey(x => x.RequestId);
        Property(x => x.Description).IsRequired().HasMaxLength(255);

        HasOptional(x => x.Notification)
            .WithWhat?
    }
}

使用 HasOptional(x => x.Notification) 就足够了,你不需要 WithMany

你没有很多 Request 具有相同的 Notification

public class Request
{
    public int RequestID { get; set; }
    public string Description { get; set; }
    public int? NotificationId { get; set; }
    public Notification Notification { get; set; }
}

public class Notification
{
    public int NotificationId { get; set; }
    public string Description { get; set; }
    public DateTime CreateDate { get; set; }
}

public class RequestMap : EntityTypeConfiguration<Request>
{
    public RequestMap()
    {
        HasKey(x => x.RequestID);
        Property(x => x.Description).IsRequired().HasMaxLength(255);
        HasOptional(x => x.Notification);
    }
}

和生成的迁移

public partial class initial : DbMigration
{
    public override void Up()
    {
        CreateTable(
            "dbo.Notifications",
            c => new
                {
                    NotificationId = c.Int(nullable: false, identity: true),
                    Description = c.String(),
                    CreateDate = c.DateTime(nullable: false),
                })
            .PrimaryKey(t => t.NotificationId);

        CreateTable(
            "dbo.Requests",
            c => new
                {
                    RequestID = c.Int(nullable: false, identity: true),
                    Description = c.String(nullable: false, maxLength: 255),
                    NotificationId = c.Int(),
                })
            .PrimaryKey(t => t.RequestID)
            .ForeignKey("dbo.Notifications", t => t.NotificationId)
            .Index(t => t.NotificationId);

    }       
    public override void Down()
    {
        DropForeignKey("dbo.Requests", "NotificationId", "dbo.Notifications");
        DropIndex("dbo.Requests", new[] { "NotificationId" });
        DropTable("dbo.Requests");
        DropTable("dbo.Notifications");
    }
}