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

时间:2017-08-11 16:47:52

标签: c# sql 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; }
}

我想要做的查询很简单:context.Test.ToList(); 这将返回数据库映射Reference为null,因为它不是表的一部分。

现在,如果我创建一个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();

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

4 个答案:

答案 0 :(得分:2)

不要选择一个匿名对象,只需从你拥有的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();

答案 1 :(得分:2)

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

像往常一样,典型的解决方法是将查询拆分为两部分 - 一部分是LINQ to Entities查询选择必要的数据(通常是中间匿名类型),然后切换到LINQ to Objects 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(); 内的块:

10.0.0.0/16

答案 2 :(得分:0)

请尝试以下操作:

(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();

答案 3 :(得分:0)

尝试:

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();
相关问题