ASP.NET MVC + EF 4.3.1 + DbContext - 一些空关联

时间:2012-06-06 00:29:00

标签: asp.net-mvc entity-framework

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

我遇到的问题是EF在我预期的某些情况下不会填充关联。我是否需要采取措施来触发所有协会的人口?

例如,我有一个Assignment模型,其中包含属性“CompanyPartyId”和“EmployeePartyId”。这两个属性都有缔约方的FK .PartyId。这导致存在两个关联,Party(指向CompanyPartyId指定的Party)和Party1(指向EmployeePartyId指定的Party)。

出于某种原因,在保存新的Assignment并检索它之后,Party关联为null。 CompanyPartyId和EmployeePartyId属性都设置为Parties.PartyId中存在的值。我和其他几个属性/协会有类似的问题;属性不为null并包含有效值,但关联为null。

如果相关,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();
}

0 个答案:

没有答案