递归解析实体框架中的用户参考

时间:2015-05-17 11:34:03

标签: asp.net entity-framework

在我的ASP.NET应用中检索数据对象时,我不太清楚我的用户引用会发生什么。代码草图:

public class DataPoint
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long Id { get; set; }

    public ApplicationUser Owner { get; set; }

    // data
}

这是来自控制器的代码,用于创建这些数据实体:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create(DataPoint dataPoint)
{
    var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());   
    dataPoint.Owner = user;
    // ...
}

现在,当我检查数据库时,DataPoint记录的ID会引用正确的ApplicationUser ID。但是在查找DataPoint这样的时候:

DataPoint dataPoint = await db.DataPoints.FindAsync(id);

除了&#34;所有者&#34;之外,所有数据字段都按预期填充。字段,null。这是为什么?我是否必须触发解析此引用?

2 个答案:

答案 0 :(得分:1)

那是因为

  1. db.DataPoints.FindAsync(id);完全相同:找到DataPoint id标识的Owner。您没有要求包含db.DataPoints.Include(d => d.Owner).Single(d => d.Id == id) 。如果你想要你应该这样做:

    Owner

    这称为急切加载

  2. public virtual ApplicationUser Owner { get; set; } 无法按需加载(即通过延迟加载),因为要发生这种情况,该属性必须是虚拟的:

    DataPoint

    现在EF将为Owner创建一个动态代理对象,一旦访问它就会从数据库中加载char StrTxt[500]; // TextAddress: The memory address of the string ReadProcessMemory(hProcess, (LPCVOID)(TextAddress), &StrTxt, sizeof(StrTxt) / sizeof(*StrTxt), 0); toClipboard(StrTxt); cout << StrTxt << endl; 。 (虽然上下文仍然存在,但没有处理)。

答案 1 :(得分:0)

您应该为同一字段定义两个属性以使关系起作用。属性public ApplicationUser Owner它被称为导航属性(您将使用它来导航到引用的实体)。模型中缺少的是包含表的外键的实际字段。

您应该像这样编辑模型:

public class DataPoint
{
    [Key]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public long Id { get; set; }
    public int OwnerId { get; set; } //read the note below


    public ApplicationUser Owner { get; set; }

    // data
}

注意: 显然,只有当包含FK的字段是整数并且它的名称遵守关系的实体框架命名约定时,一切都在上面的代码中正常工作:

ReferencedTableName   => name of the target table
Id                    => referenced table primary key name
ReferencedTableNameId => referencing field (in referencing table)

如果数据库scheam不符合命名约定,则必须手动设置与ModelBuilder对象的关系或使用数据注释属性。