Update collection from DbSet object via Linq

2019-08-27 21:39发布

问题:

i know it is not complicated but i struggle with it.

I have IList<Material> collection

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

And i have DbSet<Material> collection with columns Number and ValueColumn

I need to update IList<Material> Value property based on DbSet<Material> collection but with following conditions

  • Only one query request into database
  • The returned data from database has to be limited by Number identifier (do not load whole database table into memory)

I tried following (based on my previous question)

Working solution 1, but download whole table into memory (monitored in 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);

Working solution 2, but it execute query for each item in the collection.

model.Materials.ToList().ForEach(m => m.Value= db.Material.FirstOrDefault(db_m => db_m.Number.ToString() == m.Number).Value);

Incompletely solution, where i tried to use contains method

// 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});

Any idea ? For me it is much easier to execute stored procedure with comma separated id values as a parameter and get the data directly, but i want to master linq too.

回答1:

I'd do something like this without trying to get too cute :

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 { ... }