0

我正在使用带有 EF 4.3.1 的 ASP.NET MVC 3 和“EF 4.x DbContext Generator for C#”扩展。我正在使用存储库模式。

我遇到的问题是,在某些情况下,我希望 EF 不会填充关联。我需要做些什么来触发所有协会的人口吗?

例如,我有一个包含属性“CompanyPartyId”和“EmployeePartyId”的分配模型。这两个属性都有针对 Party.PartyId 的 FK。这会导致存在两个关联,Party(指向 CompanyPartyId 指定的 Party)和 Party1(指向 EmployeePartyId 指定的 Party)。

出于某种原因,在保存并检索新任务后,党的关联为空。CompanyPartyId 和 EmployeePartyId 属性都设置为存在于 Party.PartyId 中的值。我对其他几个属性/关联有类似的问题;属性不为空且包含有效值,但关联为空。

如果相关,Assignment 使用复合键;CompanyPartyId、EmployeePartyId、AssignmentTypeCode 和 AssignmentStartDate。

我的控制器中的代码如下所示(省略验证和不相关的逻辑):

[HttpPost]
[Authorize(Roles = "assignment_edit")]
public ActionResult Create(AssignmentViewModel assignment)
{
    var newAssignment = assignment.NewAssignment;
    partiesRepository.SaveAssignment(newAssignment);

    var savedAssignment =
        partiesRepository.Assignments.First(x => x.CompanyPartyId == newAssignment.CompanyPartyId &&
                                                 x.EmployeePartyId == newAssignment.EmployeePartyId &&
                                                 x.AssignmentTypeCode == newAssignment.AssignmentTypeCode &&
                                                 x.AssignmentStartDate == newAssignment.AssignmentStartDate);
    var companyPartyId = savedAssignment.CompanyPartyId; // 1
    var companyParty = savedAssignment.Party; // null
    var employeePartyId = savedAssignment.EmployeePartyId; // 2
    var employeeParty = savedAssignment.Party1; // not null

    return View("Index");
}

存储库代码很简单:

public IQueryable<Assignment> Assignments
{
    get { return _context.Assignments; }
}

public void SaveAssignment(Assignment assignment)
{
    var data = (from a in _context.Assignments
                where a.CompanyPartyId == assignment.CompanyPartyId
                      && a.EmployeePartyId == assignment.EmployeePartyId
                      && a.AssignmentTypeCode == assignment.AssignmentTypeCode
                      && a.AssignmentStartDate == assignment.AssignmentStartDate
                select a);
    if (!data.Any())
    {
        _context.Assignments.Add(assignment);
    }
    _context.SaveChanges();
}
4

0 回答 0