对照Java进行C#的快速入门实战(对新手上手友好)

发布于:2024-08-11 ⋅ 阅读:(115) ⋅ 点赞:(0)

1. git拉取项目

2. 启动项目

  • 打开后缀为sln的文件
  • 查看相关依赖配置(程序包)
  • 一般在Properties文件夹下会有launchSetting.json,在里面修改自己的ip

3. 目录结构

  • 和Java类似,但不同的在于Java的service、mapper层在C#中,用Dals表示
  • Controller
  • Dals
  • Models
  • Utils
  • Views

4. 接口编写

  • 先在controller写个接口,跟Java一样
  • 剩下的逻辑和sql都可以在Dals中写,也可以把sql分离出去,写个公共的
    代码如下:
    Controller:
namespace Demo.Controllers
{
    [Route("api/[Controller]")]
    public class ResultController : Controller
    {
        ResultDal resultDal= new ResultDal();
        [HttpPost]
        [Route("getResult")]
        public object getResult(int id, int type, int page = 1, int size = 10)
        {
            try
            {
                return resultDal.getResult(id,  type, page,size);
            }
            catch (Exception ex)
            {
                return Utility.toJsonResult(ex.Message, false);
            }
        }
    }
}
namespace Demo.Dals
{
    public class ResultDal : ResultModel
    {
        //postsql数据库连接
        public static PostsqlHelper postsqlHelper = new PostsqlHelper();
        public object getResult(int id, int type, int page, int size)
        {
            string resultJson = string.Empty;
            try
            {
                string where = "";
                where += string.Format(" and id ='{0}'", id);
                where += string.Format(" and type ='{0}'", type);
                string sql = string.Format(@"select id,result,type,st_astext(shape) from sjk1.result where 1=1 {0}", where);
                sql += string.Format(" limit {0} offset {1}", size, (page - 1) * size);
                string sql_count = string.Format(@"select count(0) from sjk1.result where 1=1 ", where);
               //string sql = string.Format(@"insert into sjk1.result(id,type) values(:id,:type) ");
               //NpgsqlParameter[] pms = new NpgsqlParameter[]
               //{
               //    new NpgsqlParameter("id",id),
               //    new NpgsqlParameter("type",type)
               // };
                Dictionary<string, object> getResult = new Dictionary<string, object>();
                getResult.Add("total", Convert.ToInt16(postsqlHelper.GetList(sql_count)[0]));
                getResult.Add("data", postsqlHelper.GetListDic(sql));
                return resultJson = Utility.toJsonResult(getResult, true);
            }
            catch (Exception ex)
            {
                throw new InvalidOperationException("Error fetching general view data.", ex);
            }
        }
   }
}

5. 小结

sql编写中

  • 条件用where拼接
  • 执行用NpgsqlParameter的方法的格式是冒号+字段

网站公告

今日签到

点亮在社区的每一天
去签到