ModelState.isValid()==False + 必需符号

ModelState.isValid()==False + Required-notation

我正在为我的项目使用 Identity 框架,并添加了一些属性,例如 JobExperienceUser class。

用户应该可以将 JobExperience 添加到他们的 User。自然地,这意味着 JobExperience 不应该在没有 User 的情况下存在。

出于这个原因,我在 JobExperienceclass

中使用了 [Required]-notation

工作经验class

public class JobExperience
{
    public int JobExperienceId { get; set; }
    public string Employer { get; set; }
    public DateTime? DateOfEmployment { get; set; }
    public DateTime? DateOfExit { get; set; }
    public ICollection<Subject> Subjects { get; set; }
    [Required]
    public virtual User ApplicationUser { get; set; }
}

用户class

public class User : IdentityUser
{
    public Boolean Available { get; set; }
    public Boolean ActivelySeeking { get; set; }
    public Boolean AcceptedUseOfData { get; set; }
    public int ExpectedHourlySalary { get; set;}
    public Boolean Gender { get; set;}
    public DateTime? DateOfBirth { get; set; }
    public String FirstName { get; set; }
    public string LastName { get; set; }
    public ICollection<JobExperience> JobExperiences { get; set; }
    public ICollection<Language> Languages { get; set; }
    public ICollection<Certificate> Certificates { get; set; }
}

脚手架JobExperienceController - 创建方法

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create([Bind(Include = "JobExperienceId,Employer,DateOfEmployment,DateOfExit")] JobExperience jobExperience)
{
    var UserId = User.Identity.GetUserId();
    jobExperience.ApplicationUser = db.Users.Where(x => x.Id == UserId).First();

    if (ModelState.IsValid)
    {
       db.JobExperiences.Add(jobExperience);
       db.SaveChanges();
       return RedirectToAction("Index");
    }

    return View(jobExperience);
}

在创建方法中添加必需符号后 modelstate.isValid() returns false。我猜它需要接收对用户的引用,但我不知道如何去做。当前尝试是显示的 LINQ 表达式。

ApplicationUserDb

 public class ApplicationUserDb : IdentityDbContext<User>
{

    public virtual DbSet<JobExperience> JobExperiences { get; set; }
    public virtual DbSet<Language> Languages { get; set; }
    public virtual DbSet<Certificate> Certificates { get; set; }

    public ApplicationUserDb() : base("DefaultConnection")
    {

    }

    internal static ApplicationUserDb Create()
    {
        return new ApplicationUserDb();
    }

}

您想将 User <-> JobExperience 之间的关系建模为 1(必需)<-> 0-N(可选列表)。您无法通过将 ApplicationUser 标记为 [Required] 来实现此目的。相反,在 ModelBuilder 中配置多重约束并删除 [Required] 属性。

ModelBuilder.Entity<User>()
   .HasMany(u => u.JobExperiences)
   .WithRequired(j => j.ApplicationUser)
   .WillCascadeOnDelete(true);

教程:Configure One-to-Many Relationships in EF 6

进一步说明,您应该引入 ViewModel,而不是将您的实体模型绑定到控制器。这样您就不会混合用于前端验证的注释(例如 [Required])和用于数据持久化的注释(例如 [ForeignKey])。

如果 User 继承自 IdentityUser,还要确保在您的模型构建器中调用 base.OnModelCreating(modelBuilder)(参见 EntityType 'IdentityUserLogin' 没有定义键. 定义此 EntityType 的键 ).