How to set value for Linq object during query?

I have a simple request as below

var trips = from t in ctx.Trips
            select t;

The problem is that I have an additional property in the Trip object that needs to be assigned, preferably without repeating through the returned one IQueryable.

Does anyone know how to set a value during a query? (i.e. select t, t.property = "value")

+3
source share
3 answers

First of all, if you never repeat the results, your code will not work. LINQ is "lazy," which means it computes the next result when you request it.

, , , - :

Trip SetProperty(Trip t)
{
    t.property = "value";
    return t;
}
var trips = from t in ctx.Trips select SetProperty(t);
+5

:

var trips = from t in ctx.Trips select new Trip 
{
    // db properties
    t.ID,
    t.Name,
    t.Description,

    // non-db properties
    SomeValue = 45,
    SomeOtherValue = GetValueFromSomewhereInCode(t.ID)
}

"" Trip, , LINQ to SQL, . , , SQL, .

Trip , ( SubmitChanges(), Trip).

, Trip LINQ to SQL. , .

+1

Trips, .

, Trips , , , where.

, ..

LINQ to SQL :

using (var context = new DefaultDataContext())
{
    var defects = context.Defects.Where(d => d.Status==Status.Open);             

    foreach(Defect d in defects)
    {
        defect.Status = Status.Fixed;                     
        defect.LastModified = DateTime.Now;
    }
    context.SubmitChanges();                 
}
0

Source: https://habr.com/ru/post/1732952/


All Articles