c#使用dynamic关键字传输数据的用法
问:
在实际开发中,特别是在ORM框架的基础下,我们返回的数据都是强类型的实体对象。如果是单表查询我们就可以直接返回对应的实体,如果是多表联合查询,我们可能就需要各个表中都返回一部分字段,组成一个新的数据集合。那么在这种情况下我们该怎么办呢?
答:
传统的方式是我们定义一个新的实体类,作为返回的符合数据的载体。而今天我将介绍一种新的方式,在不用重新定义传输实体的基础上,解决这个问题。
代码如下:
1.首先定义测试数据实体,模拟对应的两张关联表:
public class student { public int id { get; set; } public string name { get; set; } public int age { get; set; } } public class address { public int id { get; set; } public int student_id { get; set; } public string city { get; set; } }
2.数据测试方法如下:
public string DynamicTest() { List<student> students = new List<student>() { new student(){ id=1,age=33,name="jack"}, new student(){ id=2,age=12,name="tom"}, new student(){ id=3,age=22,name="lily"}, new student(){ id=4,age=66,name="wjh"} }; List<address> addresss = new List<address>() { new address(){ id=1,student_id=2,city="北京"}, new address(){ id=2,student_id=1,city="上海"}, new address(){ id=3,student_id=1,city="南京"}, new address(){ id=4,student_id=3,city="苏州"} }; dynamic data=(from s in students join a in addresss on s.id equals a.student_id where s.age>12 select new { name = s.name, city = a.city } ).ToList(); foreach (var item in data) { var s = item.name; var city = item.city; } return "s"; }
注意:dynamic 对应的类型运行时才确定,并且生成的是内部类,所以只能在当前程序集中使用,使用dynamic在返回json的场景中使用比较方便。