我有以下模型,我试图在 Request
对象上将 Notification
属性归为null或通知的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");
}
}