1
votes

I have a property that is required on my entity. Upon adding the entity to the database, that property is populated by the system. From here on, this property should never be changed. This property is also never passed to the client.

So now when the user edits this entity, and it is passed to my service layer, the property is null. Is it possible to tell EF that this property should not be modified and never updated, or is my only option, to retrieve the value from the database and populate the edited entity with the same value before SaveChangesAsync is called?

Here is an example of my entity

public myEntity() {
    public long Id { get; set; }

    public string Name { get; set; }

    public string SystemProperty { get; set; }
}

Only the properties Id and Name are passed to the client. When AddAsync is calling in my service, i populate SystemProperty myself.

Here is my UpdateAsync, which is making DbContext throw an exception of

SystemProperty is required

public override Task<int> UpdateAsync(Module updated)
{
    _context.Modules.Attach(updated);

    // do not update
    _context.SetModified(updated, "SystemProperty", false);

    return _context.SaveChangesAsync();
}

My SetModified method has been created against my DbContext so i can unit test the method.

public void SetModified(object entity, string property, bool isModified)
{
    this.Entry(entity).Property(property).IsModified = isModified;
}

As you can see, i thought i could use the IsModified = false, but that doesnt seem to ignore the property.

What are my options?

1

1 Answers

1
votes

Best workaround I know:

entity.Property = "placeholder";

var entry = _context.Entry(entity);
entry.State = EntryState.Modified;
entry.Property(m => m.Property).IsModified = false;

_context.SaveChanges();

You mark entity as modified and then exclude not modified properties. As for validation, you need to set valid value for that field just to pass validation.