视图模型对象转换为实体框架对象 [英] ViewModel Object Convert to Entity Framework Object

查看:173
本文介绍了视图模型对象转换为实体框架对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目标:通过实体框架保存视图模型对象。其中有 UnitViewModel 的名单上有 UserViewModel 对象。然后,我有其中转换的 UserAdapter UserViewModel 进入实体框架用户对象(请参阅转换()下面如何)。

Goal: to save ViewModel object by Entity Framework. I have UserViewModel object which has list of UnitViewModel. Then, I have a UserAdapter class which converts UserViewModel into Entity Framework User object (see Convert()below how).

现在,我的问题是我怎么转换 UnitViewModel 的这个名单到其相应的实体框架单位列表? - 我必须通过调用类似 context.Units.Where摆脱DB语境每个对象(U => myListofUnitIDs.Contains(u.UnitID))

Now, my question is how do I convert this list of UnitViewModel to its corresponding Entity Framework Unit list? - Do I have to get each object from DB Context by calling something like context.Units.Where(u=>myListofUnitIDs.Contains(u.UnitID))?

public class UserViewModel
{
    public Guid? UserID { get; set; }
    public string UserName { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Password { get; set; }
    public DateTime? CreateTime { get; set; }
    public List<UnitViewModel> UserUnits { get; set; }
}


public class UnitViewModel
{
    public Guid UnitID { get; set; }
    public string Name { get; set; }
    public int? SortIndex { get; set; }
    public DateTime CreateTime { get; set; }
    public bool Assigned { get; set; }
}


public class UserAdapter
{
    public static User Convert(UserViewModel userView)
    {
        User user;
        if (userView.UserID.HasValue)
        {
            using (var provider = new CoinsDB.UsersProvider())
            {
                user = provider.GetUser(userView.UserID.Value);
            }
        }
        else
        {
            user = new User();
        }

        user.FirstName = userView.FirstName;
        user.LastName = user.LastName;
        user.Password = StringHelper.GetSHA1(userView.Password);
        user.UserName = user.UserName;
        user.CreateTime = DateTime.Now;

        // Problem here :)
        // user.Units = userView.UserUnits;

        return user;
    }
}

更新:这里的主要问题是,我要检索每个单位从数据库匹配(或地图),它与 ViewModel.Unit 对象,对不对?我能否避免呢?

UPDATE: The main concern here is that I have to retrieve each Unit from database to match (or map) it with ViewModel.Unit objects, right? Can I avoid it?

推荐答案

有关您的信息,该操作被称为的映射的为主。所以,你要到您的视图模型对象映射到实体对象。

For your information, this operation is called as Mapping mainly. So, you want to map your view model object to the entity object.

对于这一点,你可以使用已经存在的第三方库的<一个href=\"https://www.google.co.uk/url?sa=t&rct=j&q=&esrc=s&source=web&cd=3&ved=0ahUKEwiD_rGsqdPJAhWBbhoKHX2QC_QQFggtMAI&url=https%3A%2F%2Fwww.nuget.org%2Fpackages%2FAutoMapper&usg=AFQjCNFI8zunKaCCH_n5MDw5L4uFzYEwUA&sig2=RNhpsaIZFt9SRi-oRdvyXg&cad=rja\"相对=nofollow> AutoMapper 。它将与相同的名称映射的属性,还可以添加使用您的定制逻辑方法后。

For this, you can either use already existed 3rd party library as AutoMapper. It will map properties with same name, also you can add your custom logic with After method.

foreach(var item in userView.UserUnits)
{
     // get the mapped instance of UnitViewModel as Unit
     var userUnit = Mapper.Map<UnitViewModel, UserUnit>(item);
     user.Units.Add(userUnit);
}

不过,我建议编写自定义映射器。因为,它可以是问题,改变在未来视图模型一个属性的名称,AutoMapper不会再处理这一点,你不会得到这个任何警告。
例如,我创建了一个定制库,这和其映射对象LIK这样的:

But, I recommend to write your custom mappers. Because, it can be problem to change the name of one property in the view model in the future, and AutoMapper will not handle this anymore and you won't get any warning about this. For example, I have created a custom library for this and it maps objects lik this:

 user.Units = userView.UserUnits
       .Select(userUnitViewModel => userUnitViewModel.MapTo<UserUnit>())
       .ToList();

和我实现这些映射函数为:

And I am implementing these mapping functions as:

 public class UserUnitMapper:
        IMapToNew<UnitViewModel, UserUnit>
    {
        public UnitViewModel Map(UserUnit source)
        {
            return new UnitViewModel
            {
                Name = source.Name,
                ...
            };
        }
    }

然后在运行时,我检测类型将映射过程中使用的对象,然后调用地图方法。这样一来,你的映射器将会从你的行动方法分隔。但是,如果你想迫切,当然你也可以使用这样的:

And then in runtime, I am detecting the types of the objects which will be used during mapping, and then call the Map method. In this way, your mappers will be seperated from your action methods. But, if you want it urgently, of course you can use this:

foreach(var item in userView.UserUnits)
{
     // get the mapped instance of UnitViewModel as Unit
     var userUnit= new UserUnit()
           {
               Name = item.Name,
               ...
           };

     user.Units.Add(userUnit);
}

这篇关于视图模型对象转换为实体框架对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆