![](/img/trans.png)
[英]EF Code First foreign key without navigation property, but with parent collection property
[英]EF Code First: Only set the foreign key(ID) and get a null collection of navigation property
感謝您的回復,為了更清楚,我重新組織了我的問題如下:
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; }
}
步驟 1> 保存數據
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();;
}
}
}
步驟 2> 獲取數據
class Program
{
static void Main(string[] args)
{
using (TestContext context = new TestContext())
{
var builds = context.Apps.FirstOrDefault().Builds;
Console.Read();
}
}
}
var 構建得到一個空值,而我檢查數據庫時,外鍵值保存得很好。
可能是你本地的EF沒有用App的新合集刷新。 您可能需要從數據庫中刷新 App 對象。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.