我正在为项目使用Identity框架,并已向JobExperience
类添加了一些属性,例如User
。
用户应该可以在其JobExperience
中添加User
。自然地,这意味着JobExperience
在没有User
的情况下不应该存在。
因此,我在JobExperience
类中使用[Required]表示法
JobExperience类
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; }
}
用户类别
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);
}
添加了Required-notation后,create方法中的modelstate.isValid()返回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。
进一步说明,您应该引入ViewModels而不是将实体模型绑定到控制器。这样,您就不会混合用于前端验证的注释(例如
[Required]
)和用于数据持久性的注释(例如[ForeignKey]
)。如果
User
从IdentityUser
继承,还请确保在您的ModelBuilder中调用base.OnModelCreating(modelBuilder)
(请参见EntityType 'IdentityUserLogin' has no key defined. Define the key for this EntityType)。