首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Code-first -通过键获取子实体

Code-first -通过键获取子实体
EN

Stack Overflow用户
提问于 2012-08-15 06:15:27
回答 2查看 102关注 0票数 0

我首先使用的是Entity Framework 4.3.1 Code,我的代码类似于下面的代码:

代码语言:javascript
复制
class Program
{
    static void Main(string[] args)
    {
        // get LogEntry with id x..
    }
}

public class MyContext : DbContext
{
    public DbSet<Log> Logs { get; set; }
}

public class Log
{
    public int LogId { get; set; }
    public ICollection<LogEntry> LogEntries { get; set; }
}

public class LogEntry
{
    public int LogEntryId { get; set; }
}

在给定整数LogEntryId的情况下,获取LogEntry对象的最佳方法是什么?可以不通过Log.LogEntries属性直接获取实体吗?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-08-15 06:34:41

如果您有上下文的引用,那么

代码语言:javascript
复制
var entry = context.Set<LogEntry>().Find(entryId);
票数 2
EN

Stack Overflow用户

发布于 2012-08-15 06:34:40

您的上下文中没有DbSet< LogEntry >有什么原因吗?

如果您这样做了,您将能够直接从上下文中加载它。

代码语言:javascript
复制
public class MyContext : DbContext
{
    public DbSet<Log> Logs { get; set; }
    public DbSet<LogEntry> LogEntries { get; set; }
}

var logEntry = context.LogEntries.SingleOrDefault(le => le.LogEntryId == someLogEntryId);
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11961610

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档