实体框架 - 在一端没有导航属性的情况下确定关系是否存在

时间:2011-12-02 15:58:52

标签: c# .net entity-framework entity-framework-4.1

我的应用程序中有以下两个实体(使用Code First):

public class Note
{
    public int NoteId { get; set; }
    public string Text { get; set; }
}

public class Decision 
{
    // PK/FK
    public int NoteId { get; set; }

    // other fields ...

    public virtual Note Note { get; set; }
}

我按照这样的方式配置了我的关系:

modelBuilder.Entity<Decision>().HasRequired(d => d.Note).WithOptional();

决定必须有一个注释,但注意并不总是有决定。 1:1的映射,一边是可选的。

我想在我的笔记上写一个属性,让我知道是否有决定。类似的东西:

public bool HasDecision 
{
    get
    {
        // not sure what to do here
    }
}

有没有一种方法可以做到这一点,而不是决定是Note上的延迟加载属性?

1 个答案:

答案 0 :(得分:0)

您需要进行明确的查询。没有像“标量属性的延迟加载代理”之类的东西。仅对导航属性支持延迟加载。如果要将HasDecision作为实体的属性,则您的实体必须具有对上下文的引用。我更愿意像这样创建一个存储库或服务方法:

public bool HasDecision(Note note)
{
    return _context.Decisions.Any(d => d.NoteId == note.NoteId);
}
相关问题