简体   繁体   中英

entity Framework code first approach returning list with join of two classes

public List<CarModel> getModel()
{
     var carm = from CarModels in carDBContext.CarModel
                join
                CarCompanies in carDBContext.CarCompany on CarModels.CompanyID equals CarCompanies.CompanyID
                    select new
                    {
                         modelID = CarModels.ModelID,
                         modelName = CarModels.ModelName,
                         companyID = CarModels.CompanyID,
                         comanyName = CarCompanies.CompanyName
                    }.ToString().ToList();
       return carm.ToList();
}

This my code snippet. I'm using entity framework code first approach. and want to return list by performing join in it with some other class(table).

I am getting compile tile error as

Error 6 Cannot implicitly convert type 'System.Collections.Generic.List>' to 'System.Collections.Generic.List' D:\\Prajakta Projects\\CarOiling\\CarOiling\\Models\\CarRepository.cs 102 19 CarOiling

If your CarModel has a CarCompany navigation property (as it should), that simplifies things significantly:

public List<CarModel> getModels()
{
    var models = carDBContext.CarModel.Select(c => new {
                     c.ModelID
                     c.ModelName
                     c.CompanyID
                     c.CarCompany.CompanyName
                }).ToList();
   return models;
}

See https://visualstudiomagazine.com/articles/2011/10/01/to-think-in-linq.aspx or https://coding.abel.nu/2012/06/dont-use-linqs-join-navigate/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM