2016-11-09 70 views
0

我有一个postgres数据库并使用asp.net核心mvc(+ ef)。数据库已正确创建。我有两个表'Module'和'ModuleMenu'。我想获得给定模块的所有菜单,但是我一直未能创建linq查询。NullReferenceException加入Postgres EF提供程序

形势

型号:Module.cs

namespace project.Model 
{ 
    public class Module 
    {  
     [Required] 
     public string ID { get; set; } 

     [Required] 
     public string Name { get; set; } 

     [Required] 
     public string Description { get; set; } 
    } 
} 

型号:ModuleMenu.cs

namespace project.Models 
{ 
    public class ModuleMenu 
    { 
     [Required] 
     public string ID { get; set; } 

     public int ModuleID { get; set; } 

     [Required] 
     public string Title { get; set; } 

     [ForeignKey("ModuleID")] 
     public virtual Module Module { get; set; } 
    } 
} 

ApplicationDbContext.cs

namespace project.Data 
{ 
    public class ApplicationDbContext 
    { 
     public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) 
      : base(options) 
     { 
     } 

     protected override void OnModelCreating(ModelBuilder modelBuilder) 
     { 
      base.OnModelCreating(modelBuilder); 
     } 


     public DbSet<Module> Modules { get; set; } 

     public DbSet<ModuleMenu> ModuleMenus { get; set; } 
    } 
} 

查询

public List<ModuleMenu> GetModuleMenus(){ 
    var query = from m in _dbContext.ModuleMenus 
       join mod in _dbContext.Modules on 
        m.ModuleID equals mod.ID 
       select m; 

    return query.ToList(); 
} 

错误

fail: Microsoft.AspNetCore.Diagnostics.ExceptionHandlerMiddleware[0] 
     An exception was thrown attempting to execute the error handler. 
System.NullReferenceException: Object reference not set to an instance of an object. 

谁能帮我正确地创建查询?

+1

Wouter,请阅读本帮助中心http://stackoverflow.com/help/tagging关于如何正确使用标签以及为什么不强制他们进入问题标题的话题。而是使用标题以简短的句子描述您的问题,然后人们可以从问题页面更容易地猜出他们是否可以回答您的问题 – Tseng

回答

2

这段代码是否正确?

public int ModuleID { get; set; } 

看来你可能在用于fk的类型中有错误。 下面我将类型改为字符串而不是int。

public string ModuleID { get; set; } 

基于该更新,查询可能如下所示。

public ModuleMenu[] GetModuleMenusForModule(string moduleId) 
{ 
    return _dbContext.ModuleMenus.Where(x => x.ModuleID == moduleId).ToArray(); 
} 
0

我期望模型发生错误(ModelID和ID是不兼容的类型)。如果这是正确的,你的代码应该工作。或更简单:

public List<ModuleMenu> GetModuleMenus() 
{ 
    return _dbContext.ModuleMenus.ToList(); 
}