Create fit model using linq and entity

I am new to LINQ

and I cannot get what I need. At the end, I need the following model:

public class MyModel {
     ... a quite long list of properties ...
     public List<SubModel> Submodels {get;set;}
}

      

MyModel contains a list of SubModels and there are about 50 sub-models for each model.

To get this, I write this query:

using (var db = new MyDataContext())
{
    var query = db.MyModels.As Queryable().Where(x => x.RevId == revId);
    var res = query.Join(db.MySubModels,
              pb => new { pb.Key, pb.RevId},
                f => new { f.Key, f.RevId}
              (pb, f) => new { MyModel = pb, Submodel = f });            
}

      

The above gives me an anonymous type where each item has a MyModel and a Submodel, but that's not what I want. From this I somehow have to get the structure as described above. I believe I should be grouping the data in some way or something.

EDIT I need this because later I need to add

a) one property for MyModel that will do some calculations on the "first item from the list MySubModels"

b) another property MyModel, which will do some calculations in the "third item from the list MySubModels"

and etc.

PS I can't use navigation because Join is done using two column values ​​(Key and RevId). None of them are unique in the "MyModel" and "MySubModel" entities, but the + RevId key combination will be inactive.

+3


source to share


1 answer


using (var db = new MyDataContext())
{
    var query = db.MyModels.As Queryable().Where(x => x.RevId == revId);
    var res = query
                .Join(db.MySubModels, pb => new { pb.Key, pb.RevId}, f => new { f.Key, f.RevId}, (pb, f) => new { MyModel = pb, Submodel = f })
                .AsEnumerable() //get the data and map objects
                .GroupBy(x => x.MyModel) //group them
                .Select(group => new { MyModel = group.Key, Submodels = group.Select(x => x.Submodel).ToList() });            
}

      



0


source







All Articles