实体无法从相关类加载数据

时间:2018-11-30 17:00:51

标签: entity-framework linq .net-core ef-code-first code-first

我有3个这样的类,并且我在.net上使用了代码优先实体

public class PersonModel
{
    [Key]
    public int PersonID { get; set;  }
    public string FullName { get ; set ; }
    public string Phone { get ; set ; }
    public string Adress { get; set ; }
    public int NationalNumber { get ; set ; }
    public List<SpecialtyToPersonModel> SpecialtyToPerson { get ; set ; }
}
public class SpecialtyModel
{
    [Key]
    public int SpecialtyID { get; set; }
    public string SpecialtyName { get; set; }
    public List<SpecialtyToPersonModel> SpecialtyToPerson { get; set; }
}

public class SpecialtyToPersonModel{
    [Key]
    public int SpecialtyToPersonID { get ; set ; }
    public SpecialtyModel Specialty { get; set; }
    public PersonModel Person { get;set; }
}

当我需要像这样使用specialityToPersonModel时

var db = new EntityContext();
            var aaa = db.SpecialtyToPersons;
            return aaa.ToList(); // so Simple !

或这样:

var db = new EntityContext();
            var aaa = db.SpecialtyToPersons
            .Include(x=>x.Specialty)
            .Include(x=>x.Person);
            return aaa.ToList();

,它把我带出这个错误:

Error Picture

An exception of type 'Npgsql.PostgresException' occurred in Microsoft.EntityFrameworkCore.dll but was not handled in user code: 'External component has thrown an exception.'

2 个答案:

答案 0 :(得分:0)

首先使DB变坏的是我的错,它来自db而不是代码... 我更正我的代码并运行

dotnet ef migrations add InitialCreate

dotnet ef database update

依此类推...反正Ty ...

答案 1 :(得分:0)

因此,SpecialtyToPersonModel不应看起来像这样

Public Class SpecialtyToPersonModel{
[Key]
Public int SpecialtyID { Get; Set; }
Public SpecialtyModel Specialty { Get; Set; }

Public int PersonID { Get; Set;  }
Public PersonModel Person { Get;Set; }

}