ASP.NET核心实体框架获取相关的数据对象

时间:2017-10-08 09:35:38

标签: asp.net relationship entity-framework-core ef-fluent-api

每当我试图获取相关对象时,我都会收到错误

  

对象引用未设置为对象的实例

相关代码:

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");

添加迁移和更新数据库没有错误,但我无法在Project表中找到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 = "jsmith@dummymail.com", 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

任何人都可以帮助确定我的关系定义有什么问题。

1 个答案:

答案 0 :(得分:0)

正如@ Ivan Stoev所指出的,EF Core尚不支持延迟加载。

https://docs.microsoft.com/en-us/ef/core/querying/related-data