Tom Hunter
Tom Hunter

Reputation: 5918

Code-first - get child entity by key

I'm using Entity Framework 4.3.1 Code First and I have something similar to the following:

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

What's the best way to get a LogEntry object given an integer LogEntryId? Is it possible to get the entity directly without going via the Log.LogEntries property?

Upvotes: 0

Views: 111

Answers (2)

Eranga
Eranga

Reputation: 32437

If you have a reference to the context, then

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

Upvotes: 2

Marty
Marty

Reputation: 7522

Any reason you don't have a DbSet< LogEntry > in your context?

If you did, you would be able to load it directly from the context.

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

Upvotes: 1

Related Questions