【EF__修改】Entity和DTO的转换与保存

1. 前言

 在使用EF进行数据库操作时,返回前台的ajax数据,需要的是没有状态的DTO,此时需要把entity转换为DTO,并传输到前台,

2. 返回前端ajax数据

从数据库查到对象,需要将该实体对象设置为EntityState.Detached,否则可能会关联到导航属性,从而去查询数据库。

	ExhibitorEntity exhibitor = exDbContext.exhibitor.Find(2);
	exDbContext.Entry(exhibitor).State = EntityState.Detached;
	var dto = BeanUtil.Mapper<ExhibitorEntity, ExhibitorDTO>(exhibitor);

3. 接收ajax数据

	var entity = BeanUtil.Mapper<ExhibitorDTO, ExhibitorEntity>(dto);
	exDbContext.Entry(entity).State = EntityState.Modified;
	exDbContext.SaveChanges();

4.BeanUtil代码

    public class BeanUtil
    {
        public static T Mapper<S, T>(S source)
        {
            T t = Activator.CreateInstance<T>();
            try
            {
                var s_type = source.GetType();
                var t_type = typeof(T);
                foreach (PropertyInfo sp in s_type.GetProperties())
                {
                    foreach (PropertyInfo dp in t_type.GetProperties())
                    {
                        if (dp.Name.ToUpper() == sp.Name.ToUpper())
                        {
                            dp.SetValue(t, sp.GetValue(source, null), null);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return t;
        }
    }
原文地址:https://www.cnblogs.com/kikyoqiang/p/12823318.html