Breeze / breeze.server.net

Breeze support for .NET servers
MIT License
76 stars 62 forks source link

Breeze.ContextProvider modified to allow overriding CreateEntityInfoFromJson #43

Closed mcshaz closed 8 years ago

mcshaz commented 8 years ago

Thanks for such fantastic software.

Apologies if this is not possible or represents a really bad idea from an architecture point of view. I would like to quickly and easily be able to map from a Dto to the corresponding server-model object before saving. It is worth noting the example projects referenced in the help documentation and hosted on GitHub demonstrates mapping objects to the DTO, but mapping back is marked as Todo: transform entities in saveBundle from DTO form into server-model form..

The easiest way I can see to do this (glancing at the relevant code) would be something like (untested code):

class MyContextProvider : EFContextProvider<MyDbContext>
{
    protected override  EntityInfo CreateEntityInfoFromJson(JTokenReader tokenReader, Type entityType)
    {
        var entityInfo = base.CreateEntityInfoFromJson(tokenReader, entityType);
        entityInfo.Entity= MapFromDto(entityInfo.Entity);
        return entityInfo;
    }
    private static object MapFromDto(object obj)
    {
        Type t = obj.GetType();
        if (t == typeof(DtoCustomer))
        {
              DtoCustomer customer = (DtoCustomer)entityInfo;
              return new DatabaseCustomer { Id = customer.Id .... };
        }
        return obj;
    }
}

In order to do things this way, it would be necessary for the ContextProvider.CreateEntityInfoFromJson method:

  1. to be marked virtual
  2. to have at least 1 method signature without dynamic arguments, e.g.
    protected internal EntityInfo CreateEntityInfoFromJson(dynamic jo, Type entityType) {
         return CreateEntityInfoFromJson(new JTokenReader(jo), entityType);
    }
    protected internal virtual EntityInfo CreateEntityInfoFromJson(JTokenReader reader, Type entityType) {

Is this an appropriate change to make? Are there better suggestions?

Thank you.

mcshaz commented 8 years ago

I closed this because

However I now see that there is no way to set the EntityInfo.Entity property. IMHO there should be a relatively clean and easy way to map from a DTO to the server type object.

Therefore, I am reopening this issue, although any clean working implementation to allow mapping (not just the 1 suggested) would be fantastic - perhaps just putting a protected set accessor on the EntityInfo.Entity property so that it could be used to perform the mapping operation in the BeforeSaveEntitiesDelegate

Thanks for considering.

mcshaz commented 8 years ago

I finally stumbled across how to achieve mapping within the beforesaveentities delegate at http://stackoverflow.com/questions/17163085/breeze-beforesaveentities-how-to-modify-savemap#17172152

closing issue as there is an easy workaround