EF核心代码首先插入空的父实体

时间:2018-12-16 14:04:33

标签: asp.net-mvc .net-core entity-framework-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表中。

在save方法期间,我在控制台输出中看到了以下内容:

 [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();

当我尝试具有类似效果时,我没有手动指定Model。

有人知道我做错了吗?

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

0 个答案:

没有答案