简体   繁体   中英

Populate data in C# entity from different tables

I've three tables:

Car

在此处输入图片说明

Parts

在此处输入图片说明

SubParts

在此处输入图片说明

Now I want to get data from all the three tables, which is easy by performing inner join I can easily get that. My SQL query is

Select C.Id AS CarId,C.Name AS CarName
, P.Id AS PartsId,P.Name AS PartsName
, SP.Id AS SubPartsId,SP.Name AS SubPartsName 
from Car C
INNER JOIN Parts P on C.Id=P.CarId
INNER JOIN SubParts SP on P.Id=SP.PartsId

In C# I've same entities with same properties as that of table columns and the same name as that of the table, now I want to populate data from a single query in three different entities without iterating each record returned from SQL query. Is there any that can be done in using ADO.NET or Enterprise Library(more preferable).

Use the join from LINQ.

var innerJoinQuery =
    from car in cars
    join part in parts on car.Id equals part.CarId
    join subPart in subParts on part.Id equals subPart.PartId
    select new {
        CarId = car.Id, 
        CarName = car.Name,
        PartsId = part.Id,
        PartsName = part.Name,
        SubPartsId = subPart.Id,
        SubPartsName = subPart.Name
    };

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