简体   繁体   English

如何使用LinQ to Entities查询选择两个对象之一(取决于一个对象是否为空)。

[英]How can I select one of two objects depending if one is null or not with a LinQ to Entities query.

List<IStoreItem> StoreItems = new List<IStoreItem>();             

StoreItems = repository.ProductToCatMaps.Where(x => CatList.Contains(x.ExCatID))
             .Select(x => x.ProductShell ?? x.PCBuild);

The entity classes: 实体类:

    public class ProductShell : IStoreItem
    {
    }

    public class PCBuild : IStoreItem
    {
    }

The ProductToCatMaps table contains the external category ID for each respective store item, I have two store items types: ProductShell and PCBuild. ProductToCatMaps表包含每个相应商店项目的外部类别ID,我有两种商店项目类型:ProductShell和PCBuild。 I wish to select either one depending on which is set to null, only one can contain a value (Foregn key to the respective types entry in the database ) which I need to select. 我希望根据设置为null的情况选择一个,只有一个可以包含需要选择的值(数据库中各个类型条目的Foregn键)。

The translation of your intent to SQL is going to be nigh impossible (or perhaps just improbable*), because the SQL to get the ProductShell fully populated is going to be wholly different than the sql to get PCBuild. 将您的意图转换为SQL几乎是不可能的(或可能是不可能的*),因为完全填充ProductShell的SQL与完全获得PCBuild的SQL完全不同。 I would switch directions and do the last bit of your query in memory. 我会切换方向,并在内存中执行查询的最后一部分。 Something like 就像是

StoreItems = repository.ProductToCatMaps
                       .Where(yourCondition)
                       .Select(x => new { x.ProductShell, x.PCBuild })
                       .AsEnumerable() // *** pulls above into memory
                       .Select(x => (IStoreItem)x.ProductShell ?? (IStoreItem)x.PCBuild);

*Of course, I haven't tried your approach at home, so if it does in fact work (with some modification, I assume that by asking, what you have so far doesn't function), then kudos to the EF team. *当然,我还没有在家中尝试过您的方法,因此,如果它确实可以工作(经过一些修改,我假设通过询问,您到目前为止所拥有的东西是否起作用),那么EF团队就会很荣幸。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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