ASP.net MVC:PK 和 FK 值在一对多延迟加载时不同步

ASP.net MVC: PK and FK values are not in sync on lazy loading for one-to-many

我的 tables 公司和角色具有一对多关系。我知道对于延迟加载设置,角色实体的 FK 值应该自动设置为与他在公司的 PK 值同步。在公司 table 中,我添加了一个公司实体实例,但由于某种原因,当我添加一个新的角色实体实例时,它被添加为空。我做错了什么?

这些是我的域 类 和上下文:

public class Company
{
    public Company()
    {
        Roles = new List<Role>();
        Employees = new List<Employee>();
    }

    public int CompanyId { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public string PhoneNo { get; set; }
    public string Email { get; set; }
    public virtual ICollection<Role> Roles { get; set; }
    public virtual ICollection<Employee> Employees { get; set; }
}

public class Role
{
    public Role()
    {
        RoleOverviews = new List<RoleOverview>();
    }
    public int RoleId { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public virtual Company Company { get; set; }
    public ICollection<RoleOverview> RoleOverviews { get; set; }

}

public class AppDbContext:DbContext
{
    public DbSet<Company> Companies { get; set; }
    public DbSet<Role> Roles { get; set; }
    public DbSet<RoleOverview> RoleOverviews { get; set; }
    public AppDbContext() : base("DefaultConnection")
    {
    }
}

public ActionResult Create([Bind(Include = "RoleId,Name,Description")] Role role)
{
    if (ModelState.IsValid)
    {
        db.Roles.Add(role);
        db.SaveChanges();
        return RedirectToAction("Index", "CompaniesRolesMV");
    }

    return View(role);
}

您定义的 PK_FK 关系只会确保您角色 table 中的公司字段具有有效 ID。但它不能 'guess' 它属于哪家公司,除非代码告诉它。

您在 'Create' 方法中 defining/creating 的角色需要提供 CompanyID 值。据推测,用户将从选择器 (?)

中进行选择

您可能需要在您的视图中定义公司选择器,并且您的创建方法操作应包括来自该选择器的公司 ID:

public ActionResult Create([Bind(Include = "RoleId,Name,Description,CompanyID")] Role role)
{
    if (ModelState.IsValid)
    {
        db.Roles.Add(role);
        db.SaveChanges();
        return RedirectToAction("Index", "CompaniesRolesMV");
    }

    return View(role);
}