SQL TO Linq,如何返回对象和填充属性



我有一个问题,我想创建一个返回对象列表的 LINQ 查询。

这是模型

public class Test
{
[Key]
public int ID { get; set; }
[Required]
[StringLength(5)]
public string Code { get; set; }
[Required]
[StringLength(50)]
public string Name { get; set; }
[NotMapped]
public string Reference { get; set; }
}

我想做的查询很简单:上下文。Test.ToList((; 这将返回数据库映射引用为空,因为不是表的一部分。

现在,如果我创建一个linq查询,我知道我可以选择新的{此处的所有字段} 我想避免这种情况:

select new Test
{
Reference = r,
ID = t.ID,
Code = t.Code,
Name = t.Name
}).ToList();

有没有可能做这样的事情

(from t in context.Test
join r in context.Reference on f.ID equals r.ID
select new
{
t.Reference = r.Reference,
t
}).ToList();

我想在同一查询中设置引用值,这可能吗?

LINQ to Entities 中不直接支持您询问的内容 - 既不支持投影到实体类型,也不支持表达式块,这是分配现有对象属性的唯一方法。

像往常一样,典型的解决方法是将查询拆分为两部分 - 一部分是选择必要数据的 LINQ to Entities 查询(通常为中间匿名类型(,然后切换到 LINQ to Objects withAsEnumerable()并完成其余工作 - 在这种情况下,在Select中使用块:

var result = 
(from t in context.Test
join r in context.Reference on f.ID equals r.ID
select new { t, r.Reference }
).AsEnumerable()
.Select(x =>
{
x.t.Reference = x.Reference;
return x.t;
}).ToList();

不要选择匿名对象,只需从您拥有的对象创建一个新 T。

(from t in context.Test
join r in context.Reference on t.ID equals r.ID
select new Test
{
Reference = r,
ID = t.ID,
Code = t.Code,
Name = t.Name
}).ToList();

编辑:

避免手动复制所有属性

public class Test
{
public int ID { get; set; }
public string Code { get; set; }
public string Name { get; set; }
public string Reference { get; set; }
public Test CopyWithReference(string reference)
{
var copy = (Test)this.MemberwiseClone();
copy.Reference = reference;
return copy;
}
}

然后。。。

(from t in context.Test
join r in context.Reference on t.ID equals r.ID
select t.CopyWithReference(r)).ToList();

尝试以下操作:

(from t in context.Test
join r in context.Reference on f.ID equals r.ID
select new Test() 
{
ID = t.ID,
Code = t.Code,
Name = t.Name,
Reference = r.Reference
}).ToList();

尝试:

var result = context.Test.Include("Reference").ToList();

或:

var result = context.Test.Include(t => t.Reference).ToList();

或尝试 lambda 表达式:

var result = context.Test.Select(t => new {
t,
t.Reference = t.Reference.Select(r => new { 
r.Reference })
}).AsEnumerable().Select(x => x.r).ToList();

最新更新