我们有Customer事务表,其中包含多个带外键的查找表。我们希望看到3个表连接在一起并将ViewModel绑定回Model并反向。我听说存储库不应该访问ViewModels。
(a)中 这样做的适当软件协议是什么?我还不想使用AutoMapper。我应该创建一个数据访问对象或服务,有人可以在下面为我写一个快速样本吗? 我应该在MVC中创建另一个名为Data Service的文件夹吗?我买了3本MVC书籍,但没有人讨论DTO或绑定模型< - >的ViewModels。 谢谢,
存储库:
void GetByCustomerTransactionId()
{
var result = from ct in CustomerTransaction
join pt in ProductType on pt.ProductTypeId equals ct.ProductTypeId
join ss in Status on s.StatusId equals ct.StatusId
select new all fields
}
模特:
public class CustomerTransaction
{
public int CustomerTransactionId{ get; set; },
public int ProductTypeId {get; set; }, //joins to ProductTypeTable
public int StatusID {get; set; }, //joins to StatusTypeTable
public string DateOfPurchase{ get; set; },
public int PurchaseAmount { get; set; },
}
public class ProductType
{
public int ProductTypeId{ get; set; }
public string ProductName { get; set; },
public string ProductDescription { get; set; },
}
public class StatusType
{
public int StatusId{ get; set; }
public string StatusName{ get; set; },
public string Description{ get; set; },
}
视图模型:
public class CustomerTransactionViewModel
{
public int CustomerTransactionId{ get; set; },
public string ProductName {get; set; }, //joins to ProductTypeTable
public string ProductDescription {get; set; },
public string StatusName {get; set; }, //joins to StatusTable
public string DateOfPurchase{ get; set; },
public int PurchaseAmount { get; set; },
}
答案 0 :(得分:0)
您是否考虑将AutoMapper映射到数据库对象以查看模型。是非常整洁干净的方式。
如果您不想使用AutoMapper,可能需要考虑使用静态方法。
var student = new Student { FirstName = "John", LastName = "Doe" };
var mdoel = student.ToDTO();
public static StudentViewModel ToDTO(this Student student)
{
var model = new StudentViewModel();
model.FullName = $"{student.FirstName} {student.LastName}";
return model;
}
希望这能帮到你
答案 1 :(得分:0)
public class CustomerTransactionViewModel : IViewModel
{
public int CustomerTransactionId{ get; set; },
public string ProductName {get; set; }, //joins to ProductTypeTable
public string ProductDescription {get; set; },
public string StatusName {get; set; }, //joins to StatusTable
public string DateOfPurchase{ get; set; },
public int PurchaseAmount { get; set; },
// Every view model should always have mapper from dbmodel to vm.
private void MaptoEntity(Entity e)
{
this.CustomerTransactionId = e.ID
.....
// this is also a repository that mapping db to view model.
var prod = new ProductTypeViewModel().Load(e.ProductID);
this.ProductName = prod.ProductName;
this.ProductDescription = prod.ProductDescription;
// so on.......
}
public bool Load(int id)
{
// Call data from DB.
var entity = dbcontext.Entity.Find(id);
// Map you from DB.
this.MaptoEntity(entity)
}
}
更好的结构是创建一个需要所有实现的接口IViewModel。
现在你可以打电话了
var customerViewModel = new CustomerTransactionViewModel();
customerViewModel .Load(1);