jeudi 26 mai 2016

Entity framework update with business model

I'm trying to implement a business layer into my application. The reason for this is that my (legacy) database is very complex for the use cases we have. So what I'm trying to do is the following

  1. Retrieve datamodel from the DbContext
  2. Transform the datamodel to a business model
  3. Pass it on to my controller to be used.

This works perfectly for retrieving objects, but updating them keeps giving me problems. Let me first give you (some of) my code (somewhat simplified): using System;

/* The datamodel*/
public class DataModel
{
    [Key]
    public int Id { get; set; }
    public double InterestRate { get; set; }
}

/*The business model */
public class BusinessModel
{
    public int Id { get; set; }
    public double InterestRate { get; set; }
    public bool IsHighInterest()
    {
        return InterestRate > 10;
    }
}

public class MyDbContext : DbContext
{
    public MyDbContext() : base("connectionstring")
    {
    }
    public DbSet<DataModel> DataModels { get; set; }
}

/* In reality I've got a repository here with a unit-of-work object instead of accessing the DbContext directly. */
public class BusinessLayer
{
    public BusinessModel Get(int id)
    {
        using (var context = new MyDbContext())
        {
            var dataModel = context.DataModels.FirstOrDefault(x => x.Id == id);
            BusinessModel = Transform(dataModel); //Do a transformation here

        }
    }

    public void Update(BusinessModel model)
    {
        using (var context = new MyDbContext())
        {
            var dataModel = TransformBack(dataModel);
            context.Entry<dataModel>.State = System.Data.Entity.EntityState.Modified;
            context.SaveChanges();
        }
    }
}

Obviously this isn't going to work, because entity framework cannot track the changes of the datamodel anymore. I'm looking for a design pattern where I can do these sort of things. Hope anyone of you can help me with this. In reality the datamodel is way more complex and the BusinessModel simplyfies it a lot, so just using the DataModel isn't really an option either.

Aucun commentaire:

Enregistrer un commentaire