Entity framework 商业模式更新

Entity framework update with business model

我正在尝试在我的应用程序中实现业务层。这样做的原因是我的(遗留)数据库对于我们拥有的用例来说非常复杂。所以我想做的是以下

  1. 从 DbContext 中检索数据模型
  2. 将数据模型转换为业务模型
  3. 传给我的控制器使用。

这非常适合检索对象,但更新它们总是给我带来问题。让我先给你(一些)我的代码(有点简化): 使用系统;

/* 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();
        }
    }
}

显然这行不通,因为 entity framework 无法再跟踪数据模型的更改。我正在寻找一种可以做这些事情的设计模式。希望你们中的任何人都可以帮助我。实际上,数据模型要复杂得多,而 BusinessModel 将其简单化了很多,因此仅使用 DataModel 也不是一个真正的选择。

基本上 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 非常适合这个。

所以在我的更新代码中我做了这样的事情(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();
}

如果您可以访问 Pluralsight,这里有一个关于该主题的精彩视频:https://wildermuth.com/2015/07/22/Mapping_Between_Entities_and_View_Models