Search code examples
c#entity-frameworkcode-first

EF Code First: Only set the foreign key(ID) and get a null collection of navigation property


Thanks for the replies, to be more clare, i have re-orged my question as follows:

 public class App
{
    [Key]
    public Guid Id { get; set; }

    public virtual IEnumerable<Build> Builds { get; set; }
}

public class Build
{
    [Key]
    public Guid Id { get; set; }

    public Guid AppId { get; set; }

    [ForeignKey("AppId")]
    public virtual App App { get; set; }
}


public class TestContext : DbContext
{
    public TestContext() : base("name=DefaultConnection")
    {
        Database.SetInitializer<TestContext>(new CreateDatabaseIfNotExists<TestContext>());
    }

    public DbSet<App> Apps { get; set; }
    public DbSet<Build> Builds { get; set; }
}

Step 1> Save Data

 class Program
{
    static void Main(string[] args)
    {
        using (TestContext context = new TestContext())
        {
            var id = Guid.NewGuid();
            App app = new App() { Id = id };
            Build build = new Build()
            {
                Id = Guid.NewGuid(),
                AppId = id
            };
            context.Apps.Add(app);
            context.Builds.Add(build);
            context.SaveChanges();;
        }

    }
}

Step 2> Get Data

class Program
{
    static void Main(string[] args)
    {
        using (TestContext context = new TestContext())
        {
            var builds = context.Apps.FirstOrDefault().Builds;
            Console.Read();
        }
    }
}

The var builds get a null value, while i check database, the foreign key value is well saved.


Solution

  • It's probably that your local EF hasn't been refreshed with App's new collection. You may need to refresh the App object from your database.

    How to Refresh DbContext