【问题标题】:Entity framework 2.1 , 2.2 : Loading related data returns Null or IncompleteEntity framework 2.1 , 2.2 : 加载相关数据返回 Null 或 Incomplete
【发布时间】:2019-05-16 03:49:32
【问题描述】:

如果您能在这方面帮助我,我们将不胜感激。

这是简化的示例:

型号:人

public int Id { get; set; }
public string Fname { get; set; }
public string Lname { get; set; }

public ICollection<TbContact> TbContact { get; set; }

型号:联系方式

public int Id { get; set; }
public string Phone { get; set; }
public string Email { get; set; }
public int PersonId { get; set; }

public TbPerson Person { get; set; }

数据库上下文:

public virtual DbSet<Blog> Blog { get; set; }
public virtual DbSet<Post> Post { get; set; }

modelBuilder.Entity<TbContact>(entity =>
{
entity.Property(e => e.Email).HasMaxLength(50);
entity.Property(e => e.PersonId).HasColumnName("Person_Id");
entity.Property(e => e.Phone).HasMaxLength(50);
entity.HasOne(d => d.Person)
.WithMany(p => p.TbContact)
.HasForeignKey(d => d.PersonId)
.HasConstraintName("FK_TbContact_TbPerson");
});
modelBuilder.Entity<TbPerson>(entity =>
{
entity.Property(e => e.Fname).HasMaxLength(50);
entity.Property(e => e.Lname).HasMaxLength(50);
});

全部由 Scaffold-DbContext 命令生成。 这是 Api 控制器:

private readonly ApiContext _context;

public PersonsController(ApiContext context)
{
_context = context;
}

// GET: api/TbPersons
[HttpGet]

public async Task<IActionResult> GetPerson()
{
var person = await _context.TbPerson.Include(x => x.TbContact).ToListAsync();
return Ok(person);
}

并且它返回 NULL 而没有编译器错误, 但如果我像下面这样删除“.include”:

public async Task<IActionResult> GetPerson()
{
var person = await _context.TbPerson.ToListAsync();
return Ok(person);
}

结果是:

[{"id":1,"fname":"Josh","lname":"R","tbContact":[]}

正如我提到的,我需要获得“tbperson”,包括“tbcontact”。

【问题讨论】:

  • 我尝试升级到 .Net core 2.2,EF Core 2.2 与上面的代码相同,结果从 null 更改为:"[{"id":1,"phone":"xxxxxxx" ,"email":"xxxx@xxx.com","personId":1,"person":{"id":1,"fname":"Josh","lname":"R","tbContact": [ "有什么建议吗???

标签: entity-framework entity-framework-core ef-core-2.1 db-first


【解决方案1】:

显然这是由于 JSON 中的自引用循环而发生的,因此我们可以通过下面的代码将其设置为关闭并解决问题:

public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApiContext>(options =>     
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))
.UseLazyLoadingProxies());

services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2)
.AddJsonOptions(options => {
options.SerializerSettings.ReferenceLoopHandling=ReferenceLoopHandling.Ignore; 
}); 
}

【讨论】:

    猜你喜欢
    • 2019-02-23
    • 1970-01-01
    • 1970-01-01
    • 2020-06-16
    • 1970-01-01
    • 2016-10-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多