Entity Framework Code First 关系保存问题

Entity Framework Code First relationship save Issue

将新员工保存到数据库时遇到一些问题。

项目模型(删除无用字段):

public class Project{
        public virtual ICollection<EmployeeManager.Employee> Employees { get; set; }
    }

EmployeeManager.Employee 型号:

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() -> 它会在数据库中创建新的项目实体。

为了 Entity Framework 在没有配置 (FluentApi) 的情况下创建正确的关系(一对多),您需要对 Employee class

进行一些更改
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; }
}