Linq to实体使用一个查询搜索多个表

时间:2014-12-07 15:30:10

标签: c# sql linq entity-framework

我一直在试着弄清楚这个问题几个小时。我需要使用Entity Framework 6在几个表中进行搜索,并且我试图使用连接使其工作完全没有运气。过了一会儿,我决定简单地将它变成几个查询,我不确定它是否理想。

以下代码有效,但它不太好,我认为(searchTerm是我的搜索查询,这是一个字符串):

// Search shareholders
var shareholders =
(from sh in ctx.FirmTypeShareholders.Where(x =>
x.CustomerID.ToString().Equals(searchTerm) ||
x.Firm_FirmType.Firm.ID.ToString().Equals(searchTerm))
    join firm in ctx.Firms on sh.Firm_FirmType.FirmID equals firm.ID
    select sh).ToList();

// Power plants by shareholder id
var powerPlantsByShareholder = (from sh in ctx.FirmTypeShareholders
                                join firm in ctx.Firms on sh.Firm_FirmType.FirmID equals firm.ID
                                from o in firm.Ownerships
                                join ppu in ctx.PowerPlantUnits on o.PowerPlantUnitID equals ppu.ID
                                join powerPlant in ctx.PowerPlants on ppu.PowerPlantID equals powerPlant.ID
                                where sh.CustomerID == 34
                                select new
                                {
                                    Shareholder = sh,
                                    PowerPlant = powerPlant
                                });

// Search persons
var persons = (from p in ctx.People.Where(x =>
x.ID.ToString().Equals(searchTerm) || x.Mobile.ToString().Equals(searchTerm) ||
x.Email.Equals(searchTerm) || x.Name.Contains(searchTerm))
                select p).ToList();

// Search power plants
var powerPlants = (from pp in ctx.PowerPlants.Where(x =>
x.ID.ToString().Equals(searchTerm) || x.GSRN.ToString().Equals(searchTerm) ||
x.EDIEL.ToString().Equals(searchTerm))
                    select pp).ToList();

有没有办法让这项工作只需一个查询?

提前致谢: - )

0 个答案:

没有答案