如何在代码第一个ASP.NET MVC 5应用程序中正确设置一对多关系中的外键约束

所以我有一个文档表和ApplicationUser表。 并且一个用户可以使用代码第一种方法上传多个文档和外键约束。 但问题是我能够保存文档而无需在Documents表中分配UserID外键ID 。 我在这里想念的是什么 以下是我的新手尝试。

ApplicationUser模型:

它是框架提供的标准模型。

文件型号:

public class Document { public int Id { get; set; } [StringLength(255)] public string FileName { get; set; } [StringLength(100)] public string ContentType { get; set; } public byte[] Content { get; set; } [StringLength(255)] public string DocumentName { get; set; } public string UserId { get; set; } [ForeignKey("UserId")] public virtual ApplicationUser User { get; set; } } 

发布行动

 [HttpPost] [ValidateAntiForgeryToken] public ActionResult Create(Document doc, HttpPostedFileBase uploadedresume) { try { if (ModelState.IsValid) { if (uploadedresume != null && uploadedresume.ContentLength > 0) { var tempdoc = new Document { FileName = System.IO.Path.GetFileName(uploadedresume.FileName), ContentType = uploadedresume.ContentType, DocumentName = doc.DocumentName }; using (var reader = new System.IO.BinaryReader(uploadedresume.InputStream)) { tempdoc.Content = reader.ReadBytes(uploadedresume.ContentLength); } _context.Documents.Add(tempdoc); } // YOU CAN CLEARLY SEE I HAVE NOT SET THE tempdoc.UserId PROPERTY WITH THE LOGGED IN USER ID // WHY AM I NOT GETTING ERROR HERE CONSTRAINT ERROR?? _context.SaveChanges(); return RedirectToAction("Create"); } } catch (RetryLimitExceededException /* dex */){ ModelState.AddModelError("", ""); } return View("Create"); } 

一对多迁移

 public override void Up() { CreateTable( "dbo.Documents", c => new { Id = c.Int(nullable: false, identity: true), FileName = c.String(maxLength: 255), ContentType = c.String(maxLength: 100), Content = c.Binary(), DocumentName = c.String(maxLength: 255), UserId = c.String(maxLength: 128), }) .PrimaryKey(t => t.Id) .ForeignKey("dbo.AspNetUsers", t => t.UserId) .Index(t => t.UserId); } public override void Down() { DropForeignKey("dbo.Documents", "UserId", "dbo.AspNetUsers"); DropIndex("dbo.Documents", new[] { "UserId" }); DropTable("dbo.Documents"); } } 

在文件表中输入:

在此处输入图像描述

预期的行为

如果我已正确设置FK约束,那么我在保存数据库时看到了约束错误。 它不应该允许NULL值,因为它不是ApplicationUserId表中的有效userId。

或者可以为空的外键是预期的行为?

也许你可以在函数onModelCreating到你的上下文文件中配置它,如下所示:

 protected override void OnModelCreating(DbModelBuilder modelBuilder) { modelBuilder.Entity() .HasMany(u => u.Documents) .WithRequired(d => d.UserId) .WillCascadeOnDelete(false); base.OnModelCreating(modelBuilder); } 

您必须在ApplicationUser类中创建一个属性来引用这样的文档:

 public ICollection Documents { get; set; } 

发生这种情况是因为你有一个关系,但这是可选的,可能是一个或没有,如果你需要强制这个关系,你必须把这个字段作为必填项:

 [Required] public string UserId { get; set; }