簡體   English   中英

EF Code First:僅設置外鍵(ID)並獲取導航屬性的空集合

[英]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 構建得到一個空值,而我檢查數據庫時,外鍵值保存得很好。

我的猜測是您正在使用預先加載並且尚未為該屬性指定Include() (可能),它看起來像

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

或者您正在使用顯式加載並且沒有調用Load() (不太可能)。

可能是你本地的EF沒有用App的新合集刷新。 您可能需要從數據庫中刷新 App 對象。

如何刷新 DbContext

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM