用选择子句扩展对象
本文关键字:对象 扩展 子句 选择 | 更新日期: 2023-09-27 17:52:41
我必须在Linq查询中填充下面的类
public class Emp
{
public string name {get; set;}
public dynamic Obj { get; set; }
public Emp()
{
Obj = new ExpandoObject();
}
}
public LoadData()
{
var emp = (from d in dbContext.Employees
select new Emp
{
name = d.name,
Obj.DOB = d.DOB,
Obj.BirthPlace = d.BirthPlace
}).ToList();
}
OR
public LoadData()
{
var emp = (from d in dbContext.Employees
select new Emp
{
name = d.name,
Obj.DOB = new ExpandoObject { DOB = d.DOB, BirthPlace = d.BirthPlace } }).ToList();
}
它不允许我像上面那样动态地分配属性,有人能帮助我如何实现这一点吗?
试试:
var emp = (from d in dbContext.Employees
select new Emp
{
name = d.name,
Obj = { DOB = d.DOB, BirthPlace = d.BirthPlace }
}).ToList();
与@gowansg答案非常相似,但没有new
关键字。它只是属性值的设置。如果我们试图得到Obj
中的Type
,我们将得到System.Dynamic.ExpandoObject
。使用new
关键字,它将是一些匿名类型。分别如下:
emp[0].Obj.OtherProperty = 1;
在使用匿名类型的情况下会失败。
你在第二个例子中很接近,你只需要设置Obj
等于new anonymous object
而不是new ExpandoObject
:
var emp = (from d in dbContext.Employees
select new Emp
{
name = d.name,
Obj = new { DOB = d.DOB, BirthPlace = d.BirthPlace }
}).ToList();
var emp = (from d in dbContext.)员工
select new Emp
{
Name = d.name,
Obj = {DOB = d.DOB,出生地= d.出生地}
}) .ToList ();