我具有以下模型,试图将Notification
对象的Request
属性设置为null或通知的ID。
但是,我不太确定如何使用流畅的映射进行映射。 HasOptional -> WithMany
似乎是我能得到的最接近的,但是我想确保NotificationId
中的Requests
列是唯一的。通过流畅的映射实现此目的的最佳方法是什么?
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?
}
}
答案 0 :(得分:1)
使用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");
}
}