zoukankan      html  css  js  c++  java
  • 【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;
            }
        }
    
  • 相关阅读:
    编码问题
    僵尸进程与孤儿进程
    进程理论 阻塞非阻塞 同步异步 I/O操作
    浏览器上网流程以及套接字介绍
    OSI七层模型
    JsonResponse返回中文乱码问题
    查看源码所在位置
    linux ssh登录的小知识
    centos7安装python3.6
    Jquery的使用
  • 原文地址:https://www.cnblogs.com/kikyoqiang/p/12823318.html
Copyright © 2011-2022 走看看