httpflow icon indicating copy to clipboard operation
httpflow copied to clipboard

[Question] Why not use context.Update(entity)?

Open ConnerOrth opened this issue 7 years ago • 6 comments

I was wondering why not use context.Update(entity) in EfRepository? When I tried to update and save an entity that contained nested entities, the provided EfRepository.Update didn't work.

Also would it be bad to make the EfRepository methods virtual?

Thanks for this clean-code starting point.

ConnerOrth avatar May 15 '19 07:05 ConnerOrth

Hi Conner,

Let's take a look at your questions. :)


Repository Method for Updating Entities

I did a little experiment to see if I could reproduce the Update issue, but unfortunately I could not. Could you checkout my branch with my experiment code and try for yourself? All you should have to do once your database is up to date (I added database migrations if you're not using the in-memory database) is run.

For the experiment I created an entity Foo, which has a child entity Bar. Each one has a property on it to update (Foo has Name and Bar has Number).

When you launch, the home page will show you the original state of Foo. Initial values are "Steve" for Name and 5 for Bar.Number:

Home

Clicking through will show you the update that was applied. If the update was fully successful, then Name should be "Scott" and Bar.Number should be 6:

Update

Within HomeController.cs you will see the update code occurring. Note that within the repository's GetById<Foo>(1) call, I manually added Include("Bar") so that the associated Bar entity would be fetched. (Otherwise, Bar would be null.)

Near the bottom you'll see two Update methods you can choose from. One uses the current code while the other uses dbContext.Update().

// Choose which Update method to call here.
_repository.UpdateUsingOriginalMethod(foo); // Original code, setting entity's state to EntityState.Modified.
// _repository.UpdateUsingDbContextUpdate(foo); // New code, calling dbContext.Update(entity).

I've tried out both, and both seem to have the same behavior.

Could you give it a try?


Virtual Repository Methods

There's certainly nothing stopping you here! The idea behind the EfRepository implementation is that you shouldn't have to create derivatives or additional repository classes. Could you elaborate on your goals for marking them virtual?

sdepouw avatar May 16 '19 11:05 sdepouw

@sdepouw First of all thanks for the quick reply and the effort you took to create a sample. I tried both of your provided methods and they both function properly. However the main difference between changing state and using context.Update(), is that the latter should do a recursive search for navigation properties/entities and change their state accordingly. This automatic search is what was needed in my case.

Regarding the virtual repository methods, the primary reason was that I needed to perform the following code.

public override async Task UpdateAsync(InteractionModelSectionItem entity)
{
	//HACK: update the (possibly changed) dialogitem type, this is a back-door type mutation.
	//see: https://github.com/aspnet/EntityFrameworkCore/issues/7510 
	dbContext.Entry(entity.DialogItem).Property("Discriminator").CurrentValue = entity.DialogItem.GetType().Name;
	dbContext.Update(entity);
	await base.UpdateAsync(entity);
}

If I didn't add dbContext.Update(), before calling the base.UpdateAsync() then my changing of nested entities would not be properly picked up. Due to the "hack/workaround" that I need to perform, I had to change the Base.UpdateAsync to virtual.

I hope that I was able to shed some light on the (perhaps odd) usecase I'm working with. If you would like anymore information please let me know.

ConnerOrth avatar May 16 '19 14:05 ConnerOrth

It sounds like a design problem if you're having entities "possibly" be mutated without you knowing about it. How is that occurring?

ardalis avatar May 16 '19 14:05 ardalis

@ardalis I'll try within the bounds of I.P. to explain the flow.

The controller action (snipped version).

[HttpPost]
[Route("{id:guid}")]
public async Task<IActionResult> Edit(Guid id, ItemViewModel itemViewModel)
{
	Item item = itemViewModel.ToItem();
	if (ModelState.IsValid)
	{
		await asyncRepository.UpdateAsync(sectionItem);		
		return RedirectToAction(nameof(Index));
	}
	return View(new ItemViewModel(item));
}

The ItemViewModel class (snipped version)

public class InteractionModelSectionItemViewModel : BaseViewModel
{	
	public BaseDialogItemViewModel DialogItemViewModel { get; set; }
	[PropertyCopy.IgnoreOnCopy]
	public string SelectedDialogItemType { get; set; }

	public Item ToItem()
	{
		Item item = new Item();
		PropertyCopy.Copy<ItemViewModel, Item>(this, item);
		item.DialogItem = DialogItemViewModel.ToDialogItem(SelectedDialogItemType);
		return item;
	}
}

The BaseDialogItemViewModel (snipped version)

public class BaseDialogItemViewModel : BaseViewModel
{	
        public string BaseProp {get;set;}
        public string FooProp {get;set;}
        public string BarProp {get;set;}

	private static readonly string @namespace = typeof(BaseDialogItem).Namespace;
	private static readonly string assemblyName = typeof(BaseDialogItem).Assembly.FullName;

	public BaseDialogItem ToDialogItem(string className)
	{
		Type type = Type.GetType($"{@namespace}.{className}, {assemblyName}");

		MethodInfo method = GetType().GetMethod(nameof(BaseDialogItemViewModel.To), BindingFlags.NonPublic | BindingFlags.Instance);
		MethodInfo generic = method.MakeGenericMethod(type);
		return (BaseDialogItem)generic.Invoke(this, null);
	}
	private TBaseDialogItem To<TBaseDialogItem>() where TBaseDialogItem : BaseDialogItem
	{
		TBaseDialogItem @base = (TBaseDialogItem)Activator.CreateInstance<TBaseDialogItem>();
		PropertyCopy.Copy(this, @base);
		return @base;
	}
}

Some information regarding PropertyCopy, this is an utility class that tries to copy all properties from obj1 -> obj2 (kinda like automapper, but reflection-based).

The BaseDialogItemViewMoved.To<>() generic method is constrained to a type of BaseDialogItem, which the database-entity equivalent of the BaseDialogItemViewModel. The main difference is that the database-entity is a hierarchy derived from the abstract BaseDialogItem. And the BaseDialogItemViewModel contains all properties of all children/derived types of BaseDialogItem. The way to determine which database-entity the viewmodel should represent is done by the ItemViewModel.SelectedDialogType property.

This in turn is the reason why if the user has a ItemViewModel.SelectedDialogType of say Foo and changes it to Bar, this should result in updating the database discriminator for the BaseDialogItem table. The reason why the //HACK: comment states "possibly changed" is because I don't check if they changed it since it was retrieved, and just set the value to the potentially changed type determined by ItemViewModel.SelectedDialogType.

(Extremely snipped version of database-entity hierachy)

public abstract class BaseDialogItem
{
	public string BaseProp {get;set;}      
}
public class FooDialogItem : BaseDialogItem
{
	public string FooProp {get;set;}
}
public class BarDialogItem : BaseDialogItem
{
	public string BarProp {get;set;}
}

If you would like some more information please let me know and I'll do my best to provide it in a timely manner.

ConnerOrth avatar May 16 '19 16:05 ConnerOrth

@yncardoso please move your question to its own ticket. This will help keep the issue tracking clean.

ConnerOrth avatar Aug 19 '19 09:08 ConnerOrth

Hi @ConnerOrth sorry I didn't follow up on this in a timely manner. If this is still an issue with the current design please re-open this issue and I'll try to sort it out. Closing.

ardalis avatar Apr 24 '20 16:04 ardalis