我有一个问题,我想创建一个返回对象列表的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();


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

最佳答案

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

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

关于c# - SQL TO Linq,如何返回对象并填充属性,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/45640085/

10-12 07:39
查看更多