简体   繁体   中英

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.

That's essentially the ViewModel pattern. While you can certainly add a repository keep in mind entity framework already implements Unit of Work, but I digress. Many of us do something very similar to your code using POCO entity models to interact with the database and then transforming those to ViewModels, DTOs, or as you call them Business Models. Automapper is great for this.

So in my update code I do something like this (MVC):

if (ModelState.IsValid)
{
    var entity = context.Entities.First(e => e.Id == viewmodel.Id); // fetch the entity
    Mapper.Map(viewmodel, entity); // Use automapper to replace changed data
    context.SaveChanges();
}

If you have access to Pluralsight here is a good video on the topic: https://wildermuth.com/2015/07/22/Mapping_Between_Entities_and_View_Models

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM