gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 12:39:20 25 4
gpt4 key购买 nike

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

 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com