簡體   English   中英

NHibernate-如何在有限制的聯接表中進行QueryOver

[英]NHibernate - How to QueryOver in joined table with restrictions

我陷入了SQL查詢(使用NHibernate 4)。

我有2個具有多對多關系的表(客戶和技術),所以我創建了一個稱為ClientTechnology的聯結表。

我正在嘗試檢索所有可用技術(非定制)加上所有可用技術(定制)並屬於給定客戶端。

在SQL中,這是以下語句:

declare @clientId int = 1

        select * from
        [dbo].[Technology] t
        where t.IsCustom = 0
        union
        select t.* from
        [dbo].[Technology] t
        join [dbo].[ClientTechnology] ct
        on ct.TechnologyId = t.Id
        where t.IsCustom = 1 and ct.ClientId = @clientId

我的客戶端流利表是:

public ClientMap()
    {
        Id(x => x.Id);
        Map(x => x.Name).Not.Nullable();
    }

對於技術表是:

public TechnologyMap()
    {
        Id(x => x.Id);
        Map(x => x.Name).Not.Nullable();
        Map(x => x.IsCustom).Not.Nullable();

        HasMany(x => x.ClientTechnologies)
            .Access.ReadOnlyPropertyThroughCamelCaseField(Prefix.Underscore)
            .Table("ClientTechnology")
            .KeyColumn("TechnologyId");
    }

最后是聯結表ClientTechnology:

public ClientTechnologyMap()
    {
        Id(x => x.Id);
        Map(x => x.Alias).Not.Nullable();
        Map(x => x.IsDeleted).Not.Nullable();

        References<Client>(x => x.Client, "ClientId");
        References<Technology>(x => x.Technology, "TechnologyId");
    }

我對實現這一目標的各種選擇持開放態度。 假設我有一個Client對象 (ClientId),我可以先檢索符合要求IsCustom = false的技術列表,然后檢索符合要求IsCustom = true的技術列表,並且“提供的客戶端是此所有者定制技術”

在必須返回技術的可枚舉的public IEnumerable<Technology> GetTechnologies(Client client)中(給定Client實例)

我嘗試了以下方法來檢索globalTechnologies:

var globalTechnologies = _session.QueryOver<Technology>()
            .WhereNot(x => x.IsDeleted)
            .WhereNot(x => x.IsCustom)
            .List();

對於所有者為客戶的customTechnologies,以下內容是:

Technology technology = null;
        ClientTechnology clientTechnology = null;
        var customTechnologies = _session.QueryOver<Technology>(() => technology)
            .JoinAlias(() => technology.ClientTechnologies, () => clientTechnology)
            .WhereNot(x => x.IsDeleted)
            .Where(x => x.IsCustom)
            .Where(clientTechnology.Client == client) //this doesn't compile
            .List();

但是我不知道如何訪問連接表(已連接)以應用限制

任何幫助將非常感激。 謝謝。

在您的情況下,唯一的問題是,您沒有在.Where()內提供Expression,因此這應該可以完成工作:

// instead of this
// .Where(clientTechnology.Client == client) //this doesn't compile
// use this
.Where(() => clientTechnology.Client == client)

但是我走得更遠。 我們應該能夠創建子查詢,

  1. 將僅返回屬於客戶端的此類Techonology.Id
  2. 然后,我們也可以使用OR並具有一個查詢,該查詢可以選擇以下對象:
    • 不是IsCustom或
    • 確實屬於客戶

如何創建子查詢,您可以在這里看到:

和OR的例子

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM