首页 > 解决方案 > EF Core 代码首先插入空的父实体

问题描述

我有以下一对实体。

public class Document : BaseEntity
{
    public Document()
    {
    }

    public StoredFile StoredFile { get; set; }
}

public class StoredFile : BaseEntity
{
    private StoredFile(string fileName, string fileLocation)
    {
        FileName = fileName;
        FileLocation = fileLocation;
    }

    public string FileName { get; set; }

    public string FileLocation { get; set; }

    public static StoredFile Create(string FileName, string FileLocation)
    {
        return new StoredFile(FileName, FileLocation);
    }
}

我有以下控制器。

    [Route("api/[controller]")]
public class FileController : Controller
{
    private readonly IFileSaver _fileSaver;
    private readonly IRepository _documentRepository;
    public FileController(IFileSaver fileSaver, IRepository documentRepository)
    {
        _fileSaver = fileSaver;
        _documentRepository = documentRepository;
    }

    [HttpPost("[action]")]
    public async Task<IActionResult> UploadDocument(IFormFile formFile)
    {
        if (formFile.Length <= 0) return Ok();
        var retVal = await _fileSaver.SaveFile(formFile);
        retVal = _documentRepository.Add(retVal);
        return Ok(new { StoredFileId = retVal.Id });
    }
}

我的存储库是添加 dbSet 和 SaveChanges 的基本通用存储库。

当我使用 UploadDocument 方法并尝试保存 StoredFile 时,它​​还会将空 Document 实体保存到 Documents 表中。

在保存方法期间,我在控制台输出中看到了类似的内容:

 [Parameters=[@p0='?' (DbType = Int32), @p1='?' (DbType = Int32), @p2='?' (DbType = Int32), @p3='?' (DbType = DateTime), @p4='?' (Size = 4000), @p5='?' (DbType = Int32), @p6='?' (DbType = Int32), @p7='?' (DbType = Int32), @p8='?' (DbType = DateTime), @p9='?' (Size = 4000), @p10='?' (DbType = Int32), @p11='?' (DbType = Int32), @p12='?' (DbType = Int32), @p13='?' (DbType = Int32), @p14='?' (DbType = Int32), @p15='?' (Size = 4000)], CommandType='Text', CommandTimeout='30']
  INSERT INTO `Documents` (`AuthorityId`, `CaseId`, `CorrespondenceCharacterId`, `DateChanged`, `Description`, `DistrictId`, `DocumentDirection`, `DocumentTypeId`, `IncomingDate`, `Lp`, `PlanId`, `ReferencedDocumentId`, `SenderId`, `SourceId`, `StoringPlaceId`, `Subject`)
  VALUES (@p0, @p1, @p2, @p3, @p4, @p5, @p6, @p7, @p8, @p9, @p10, @p11, @p12, @p13, @p14, @p15);
  SELECT `Id`
  FROM `Documents`
  WHERE ROW_COUNT() = 1 AND `Id` = LAST_INSERT_ID();

我没有手动指定模型,当我尝试时我有类似的效果。

有人知道我做错了什么吗?

PS 当我在我的 DatabasePopulator 存储 StoredFile 中使用“SeedData”方法时不会导致插入空文档。

标签: asp.net-mvc.net-coreentity-framework-core

解决方案


推荐阅读