1

(This question has been asked on SO and i have read most of the related posts and try to implement based on the suggestions but still not working)

  • I am using EF6 ( not EF Core)
  • I am also using DB first approach. So we have .edmx file and C# entities are created by edmx template ( not sure if that matters here)

I want to update certain properties of an entity without loading the entire entity.

    private async Task Monitor()
    {
        var timeStamp = DateTime.UtcNow.AddHours(-8);
        var documents = await _dbContext.Documents
                        .Where(x => x.DocumentCreatedDateTime < timeStamp)
                        .Select(x => new
                        {
                            x.DocumentID,
                            x.DocumentCreatedDateTime,
                            x.ProcessStatusID,
                            ProcessStatus = x.ProcessStatus.ProcessStatusName,
                            x.CurrentErrors,
                            x.ModifiedDateTime,
                            x.VersionStamp                                
                        })
                        .ToListAsync();

        if (documents.Count == 0)
        {
            return;
        }

        foreach (var document in documents)
        {  
            var docEntity = new Document();

            docEntity.DocumentID = document.DocumentID;
            docEntity.CurrentErrors = "Document has error";
            docEntity.ProcessStatusID = (int)StatusEnum.Error;
            docEntity.ModifiedDateTime = DateTime.UtcNow;
            docEntity.VersionStamp = document.VersionStamp;

            _dbContext.Documents.Attach(docEntity);
            var entry = _dbContext.Entry(docEntity);
            entry.Property(p => p.CurrentErrors).IsModified = true;
            entry.Property(p => p.ProcessStatusID).IsModified = true;
            entry.Property(p => p.ModifiedDateTime).IsModified = true;
            entry.Property(p => p.VersionStamp).IsModified = true;
        }           

        await _dbContext.SaveChangesAsync().ConfigureAwait(false);
    }

Issue
The document entity has several other properties (columns) that are required in the database. But this particular process does not need to update those properties. When SaveChanges() get invoked i get EntityValidationErrors error

Update 1
I think i can do db.Configuration.ValidateOnSaveEnabled = false but not sure is that is the correct approach

The xxxxx field is required.

LP13
  • 30,567
  • 53
  • 217
  • 400

0 Answers0