c# - EF 代码优先 : Only set the foreign key(ID) and get a null collection of navigation property

标签 c# entity-framework code-first

感谢您的回复,为了更清楚,我将我的问题重新整理如下:

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

第一步>保存数据

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

    }
}

第二步>获取数据

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

var 构建得到一个空值,而我检查数据库时,外键值保存完好。

最佳答案

我的猜测是您正在使用预先加载并且没有指定 Include()对于该属性(可能),它看起来像

context.Apps.Where(...).Include(a => a.Builds).ToList()

或者您正在使用显式加载并且没有调用 Load() (不太可能)。

关于c# - EF 代码优先 : Only set the foreign key(ID) and get a null collection of navigation property,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39598803/

相关文章:

c# - 在事先不知道对象类型(类/表)的情况下查询 Entity Framework 实体

asp.net - 使用 "EF-Code First"时如何定义键?

entity-framework - 添加的代码优先实体不会延迟加载属性

c# - Visual Studio 开始构建之前的长时间延迟

c# - 间歇性System.ComponentModel.Win32Exception : The network path was not found

c# - Excel VBA 代码转换

entity-framework - 是否需要为所有实体定义DataSet

c# - 如何将枚举值保存到数据库?

C# 获取 Microsoft ReportViewer 加载 XDocument 内容

c# - SQL > Linq to Sql,SQL 查询有效,Linq to SQL 返回空数据集