【问题标题】:Entity cannot load data from related class实体无法从相关类加载数据
【发布时间】:2019-05-02 20:45:19
【问题描述】:

我有 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.'

【问题讨论】:

  • 你应该有一个内部异常。

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


【解决方案1】:

起初使数据库变坏是我的错,它来自数据库而不是代码... 我更正了我的代码并运行

dotnet ef migrations add InitialCreate

dotnet ef database update

再等等...无论如何...

【讨论】:

    【解决方案2】:

    所以 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; }
    

    }

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多