Обобщение поведения с использованием ninject и automapper - PullRequest
0 голосов
/ 15 марта 2020

У меня есть этот класс, который хорошо работает:

public class DataWriter : IPersist<List<MyEntity>>
{
    private readonly MyContext _ctx;
    private readonly IMapper _mapper;

    public DataSite(MyContext ctx, IMapper mapper)
    {
        _ctx = ctx;
        _mapper = mapper;
    }

    public void SaveData(List<MyEntity> entity)
    {
        foreach (var item in entity)
        {
            // Map on MyContextEntity (the table!)
            var map = _mapper.Map<MyContextEntity>(item);

            // Attach to EF (on a specific DBSet)
            var myEntity = _ctx.MyDbSet.Attach(map);

            // Action: INSERT/UPDATE/DELETE
            if (item.MustDelete)
                _ctx.Entry(map).State = System.Data.Entity.EntityState.Deleted;
            else
            {
                // The next statement is because the table has not an Id as primary key
                var found = _ctx.MyDbSet.Any(x => x.myField== map.myField);

                _ctx.Entry(map).State = found ? EntityState.Modified : EntityState.Added;
            }
        }

        _ctx.SaveChanges();
    }
}

Интерфейс:

public interface IPersist<T>
{
    void SaveData(T entity);
}

Целевая привязка:

Bind<IRepositorySitoFactory>().ToFactory();
Bind(typeof(IPersist<>)).To(typeof(DataSite)).Named("RepositorySitoPersist");

"Именовано", потому что я хотел бы использовать в другом месте:

public interface IRepositorySitoFactory
{
    IPersist<Sito> GetRepositorySitoPersist();
}

В конце концов, менеджер класса ...

public class MyConfigurationManager
{
    private readonly IKernel _kernel;
    private readonly IMapper _mapper;

    public MyConfigurationManager(IKernel kernel, IMapper mapper)
    {
        _kernel = kernel;
        _mapper = mapper;

    }

    public void Save(MyConfiguration configuration)
    {
        // SaveBulk SITO
        var wrSito = _kernel.Get<IPersist<List<Sito>>>();
        wrSito.SaveData(configuration.MyData);
    }
}   

... и данные dto:

public class Configuration
{
    public List<Sito> Siti { get; set; }

    // Other dto objects here below...
}

Моя цель - обобщить метод SaveData, потому что для каждого объекта EF код одинаков. Что изменится, так это то, что нужно работать.

Примечания:

  1. Свойство MustDelete находится внутри каждого объекта, поэтому я могу получить его с отражением;
  2. В поисках В сущности, свойство "myField" отличается в каждой сущности, поэтому я должен как-то передать вызов метода ...

Я пробовал с обобщениями типа "", но без результатов.

...