我知道这并不复杂,但是我为此感到困惑。
我有IList<Material>
个收藏夹
public class Material
{
public string Number { get; set; }
public decimal? Value { get; set; }
}
materials = new List<Material>();
materials.Add(new Material { Number = 111 });
materials.Add(new Material { Number = 222 });
我有DbSet<Material>
个收藏
具有列 Number 和 ValueColumn
我需要根据IList<Material>
集合更新DbSet<Material>
Value属性,但要满足以下条件
我尝试了以下操作(基于之前的question)
工作解决方案1 ,但将整个表下载到内存中(在sql server profiler中监视)。
var result = (
from db_m in db.Material
join m in model.Materials
on db_m.Number.ToString() equals m.Number
select new
{
db_m.Number,
db_m.Value
}
).ToList();
model.Materials.ToList().ForEach(m => m.Value= result.SingleOrDefault(db_m => db_m.Number.ToString() == m.Number).Value);
工作解决方案2 ,但是它对集合中的每个项目执行查询。
model.Materials.ToList().ForEach(m => m.Value= db.Material.FirstOrDefault(db_m => db_m.Number.ToString() == m.Number).Value);
解决方案不完全,我尝试使用包含方法
// I am trying to get new filtered collection from database, which i will iterate after.
var result = db.Material
.Where(x=>
// here is the reasonable error: cannot convert int into Material class, but i do not know how to solve this.
model.Materials.Contains(x.Number)
)
.Select(material => new Material { Number = material.Number.ToString(), Value = material.Value});
有什么主意吗?对我来说,用逗号分隔的id值作为参数执行存储过程并直接获取数据要容易得多,但是我也想掌握linq。
答案 0 :(得分:0)
我会做这样的事情而不会变得太可爱:
var numbersToFilterby = model.Materials.Select(m => m.Number).ToArray();
...
var result = from db_m in db.Material where numbersToFilterBy.Contains(db_m.Number) select new { ... }