将新员工保存到数据库时遇到了一些麻烦。
项目模型(删除了无用的fiels):
public class Project{
public virtual ICollection<EmployeeManager.Employee> Employees { get; set; }
}
EmployeeManager.Employee Model:
public class Employee{
public virtual ApplicationUser User { get; set; }
public virtual ProjectsManager.Project ProjectObj { get; set; }
}
功能:
public async Task AddNewEmployeeAsync(string projectId, string email, string fullname){
var projectInfo = await GetByIdAsync(projectId);
var userInfo = new ApplicationUser();
if (await _context.Users.AnyAsync(_ => _.Email == email)){
userInfo = await _context.Users.FirstAsync(_ => _.Email == email);
}
else{
....
userInfo = user;
}
projectInfo.Employees.Add(new EmployeeManager.Employee{
User = userInfo
});
_context.Entry(projectInfo).State = EntityState.Modified;
_context.SaveChanges();
}
毕竟,我的数据库没有变化。
为什么呢?
如果我使用_context.Employees.Add() - &gt;它在数据库中创建新的项目实体。
答案 0 :(得分:0)
要使Entity Framework在没有配置(FluentApi)的情况下创建正确的关系(一对多),您需要对Employee类进行一些更改
public class Employee
{
public virtual ApplicationUser User { get; set; }
public int ProjectId { get; set; } //foreign key maybe a string as defined in your Project class
public virtual ProjectsManager.Project Project { get; set; }
}