我正在使用 MVVM 模式构建 WPF 应用程序。我们的堆栈如下所示:
SQL Server 2008 -> 实体框架
我们使用 StructureMap 进行依赖注入来注入我们的 DataFactory,它本质上为我们的 POCO 业务对象执行 CRUD。
ViewModel 将 DataFactory 用于 CRUD,而 xaml 是绑定到 POCO 中的属性的数据。
整个事情都很好,但我发现唯一有点烦人的是数据工厂。我们在选择时将 EF 对象中的每个属性复制到 POCO 中,而在更新/插入时则相反。
有没有办法像 Fluent 对 NHibernate 但使用实体框架一样自动化这个过程?
这是数据工厂中的示例插入方法:
public void InsertCustomer(ref Manager.Model.Customer businessObject)
{
var mgr = new Manager.Data.PersonData.PersonContext();
var person = new Manager.Data.PersonData.Person();
var customer = new Manager.Data.PersonData.Customer();
customer.Comments = businessObject.Comments;
customer.Company = businessObject.Company;
customer.IsBusiness = businessObject.IsBusiness;
customer.IsCompleted = businessObject.IsCompleted;
customer.ModifiedBy = "someone";
customer.ModifiedOn = DateTime.Now;
customer.CreatedBy = "someone";
customer.CreatedOn = DateTime.Now;
person.Customer.Add(customer);
person.FirstName = businessObject.FirstName;
person.LastName = businessObject.LastName;
person.Birthday = businessObject.Birthday;
person.CreatedBy = "someone";
person.CreatedOn = DateTime.Now;
person.Gender = businessObject.Gender;
person.MiddleInitial = businessObject.MiddleInitial;
person.ModifiedBy = "someone";
person.ModifiedOn = DateTime.Now;
person.Nickname = businessObject.Nickname;
person.Picture = "";
person.Suffix = businessObject.Suffix;
person.Title = businessObject.Title;
mgr.AddToPeople(person);
mgr.SaveChanges();
}
声明一些类会很好,就像 Fluent 那样:
public class CatMap : ClassMap<Cat>
{
public CatMap()
{
Id(x => x.Id);
Map(x => x.Name)
.WithLengthOf(16)
.Not.Nullable();
Map(x => x.Sex);
References(x => x.Mate);
HasMany(x => x.Kittens);
}
}
最后我的插入方法看起来像这样:
public void InsertCustomer(ref Manager.Model.Customer businessObject)
{
var mgr = new Manager.Data.PersonData.PersonContext();
var person = new Manager.Data.PersonData.Person();
var customer = new Manager.Data.PersonData.Customer();
Something.Map(person, businessObject);
Something.Map(customer, businessObject);
person.Customer.Add(customer);
mgr.AddToPeople(newCustomer);
mgr.SaveChanges();
}
本质上,我将消除将数据从业务对象移动到实体框架工作对象的代码,这将在映射类中完成一次,并且不必为每个方法重复。
谢谢!