2017-10-08 148 views
-1

每次我試圖得到一個相關的對象,我得到的錯誤不設置到對象ASP.NET核心實體框架獲取相關數據對象

相關代碼的實例

對象引用:

public class Project 
{ 
    public int ProjectId { get; set; } 
    public string ProjName { get; set; } 
    public string Description { get; set; } 
    public virtual List<Developer> MyDevs { get; set; } 
} 

public class Developer 
{ 
    public string Name { get; set; } 
    public string Skills { get; set; } 
    public string Email { get; set; } 
    public virtual Project MyProj { get; set; } 
} 

//define relationship using fluent api, under AppDbContext 
modelBuilder.Entity<Developer>() 
.HasOne(d => d.MyProj) 
.WithMany(p => p.MyDevs) 
.HasForeignKey("ProjectForeignKey"); 

添加遷移和更新數據庫給沒有錯誤,但我不能夠找到在項目表中的列mydev的。我無法在Developer表中找到myProj列,只有foreignkey列。

運行以下種子法增加了一個項目,一個開發商預期的分貝。

public static void Seed(IApplicationBuilder applicationBuilder) 
{ 
    AppDbContext context = applicationBuilder.ApplicationServices.GetRequiredService<AppDbContext>(); 
    Project ProjA = new Project { ProjName = "handyApp", Description = "a dummy Project" }; 
    context.Project.Add(projA); 
    Developer FirstDev = new Developer { UserName = "John Smith", Skills = "C#", Email = "[email protected]", MyProj = ProjA}; 
    context.Developer.Add(FirstDev); 
    context.SaveChanges(); 
} 

然後運行下面的代碼命中異常「未設置爲一個對象的實例對象引用」。

Developer Dev = context.Devs.Find(1); 
string name = Dev.MyProj.ProjName; //put a break point here, the dubugger tells me Dev.MyProj is null 

請任何人都可以幫助確定什麼是錯我的關係定義。

+0

*每次我試圖得到一個相關對象* - 所以顯示在您這樣做的代碼。 –

+0

關係*定義*可以。但是你需要問EF來加載(填充)導航屬性。請參見[加載相關數據](https://docs.microsoft.com/en-us/ef/core/querying/related-data)文檔主題。 –

+0

@aaron,是的,這是正確的項目編號 –

回答