How to correctly set foreign key constraint in one to many relationship in code first ASP.NET MVC 5 application

蓝咒 提交于 2019-11-29 18:01:20

Maybe you can configure this in the function onModelCreating into your context file, something like this:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {

        modelBuilder.Entity<ApplicationUser>()
            .HasMany(u => u.Documents)
            .WithRequired(d => d.UserId)
            .WillCascadeOnDelete(false);

        base.OnModelCreating(modelBuilder);
    }

You will have to create a property in your ApplicationUser class to reference the documents like this:

public ICollection<Document> Documents { get; set; }

This happens because you have a relation but this is optional, may be one or none, you have to put this field as a required if you need to make this relation mandatory:

[Required]
public string UserId { get; set; }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!