【问题标题】:Code-first - get child entity by key代码优先 - 按键获取子实体
【发布时间】:2012-08-15 06:34:40
【问题描述】:

我使用的是 Entity Framework 4.3.1 Code First,我有类似以下内容:

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 属性直接获取实体?

【问题讨论】:

    标签: c# entity-framework-4 .net-4.0 ef-code-first


    【解决方案1】:

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

    var entry = context.Set<LogEntry>().Find(entryId);
    

    【讨论】:

      【解决方案2】:

      您的上下文中没有 DbSet 的任何原因?

      如果你这样做了,你就可以直接从上下文中加载它。

      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);
      

      【讨论】:

      • 我没想到 - 即使一个 DbSet 是另一个 DbSet 的“孩子”,我也可以根据需要添加任意数量的 DbSet&lt;&gt;s 吗?
      • 是的,你当然可以。为数据库中的每个表添加一个是非常标准的。
      猜你喜欢
      • 2011-08-05
      • 2012-05-10
      • 2015-02-24
      • 2021-01-05
      • 2011-08-05
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多