Как использовать Eager Loading с полями «многие ко многим»? - PullRequest
0 голосов
/ 06 марта 2019

У меня есть модель товара с полем ArticleAuthors:

public virtual ICollection<ArticleAuthor> ArticleAuthors
{
    get; set;
}

Мой ArticleAuthor Class выглядит так

public class ArticleAuthor : BaseEntity
{
    public Guid ArticleId { get; set; }

    public Article Article { get; set; }

    public Guid AuthorId { get; set; }

    public Author Author { get; set; }
}

Авторский класс

public class Author : BaseEntity
{
    public string Name { get; set; }

    public string Email { get; set; }

    public ICollection<ArticleAuthor> ArticleAuthors { get; set; }
}

И BaseEntity

public class BaseEntity
{
    public Guid ID { get; set; }

    [Timestamp]
    public byte[] Timestamp { get; set; }

    public BaseEntity()
    {
        ID = Guid.NewGuid();
    }
}

Отношение «многие ко многим» определяется с помощью Fluent API

modelBuilder.Entity<ArticleAuthor>()
    .HasKey(bc => new {bc.ArticleId, bc.AuthorId});
modelBuilder.Entity<ArticleAuthor>()
    .HasOne(bc => bc.Article)
    .WithMany(b => b.ArticleAuthors)
    .HasForeignKey(bc => bc.ArticleId);
modelBuilder.Entity<ArticleAuthor>()
    .HasOne(bc => bc.Author)
    .WithMany(c => c.ArticleAuthors)
    .HasForeignKey(bc => bc.AuthorId);

Я определил веб-сервис для загрузки статьи

[HttpGet("{id}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesDefaultResponseType]
public async Task<ActionResult<Article>> GetArticle([FromRoute] Guid id)
{
    Article article = await _dbContext.Articles
        .Include(x => x.MainPictureFile)
        .FirstOrDefaultAsync(x => x.ID == id);

    if (article == null)
    {
        return NoContent();
    }

    return Ok(article);
}

Работает отлично, пока я не попытаюсь загрузить поле ArticleAuthors с помощью EagerLoading

[HttpGet("{id}")]
[ProducesResponseType(StatusCodes.Status200OK)]
[ProducesResponseType(StatusCodes.Status204NoContent)]
[ProducesDefaultResponseType]
public async Task<ActionResult<Article>> GetArticle([FromRoute] Guid id)
{
    Article article = await _dbContext.Articles
        .Include(x => x.MainPictureFile)
        .Include(x => x.ArticleAuthors)
        .FirstOrDefaultAsync(x => x.ID == id);

    if (article == null)
    {
        return NoContent();
    }

    return Ok(article);
}

Когда я это делаю, возвращаемый JSON обрезается после articleId :

{"title":"Editorial updated","chapo":null,"body":null,"readingTime":null,"edition":null,"date":null,"theme":null,"articleAuthors":[{"articleId":"d4ef0cfe-0b7b-4432-a099-75a221c2258b"

Я использовал эту статью для настройки своего отношения «многие ко многим»: https://www.learnentityframeworkcore.com/configuration/many-to-many-relationship-configuration

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...