3

是否可以在没有指定映射的情况下加入两个类(使用 Criteria API)?

我必须加入两个类并从两者中检索数据,但我无法映射它们。我只知道第一类中的外键SomeID和第二类中的主键ID

如何创建加入他们的标准?没有映射可以吗?

请帮助,我真的需要它,但我被卡住了。:/

附言

我知道“任何”映射,但我有 10 个字段,例如 SomeID。只为创建连接创建 10 个字段的任何映射是多余的。如果没有其他解决方案,我会这样做,但我不想这样做。

4

2 回答 2

6

我不知道标准版本,但在 HQL 中你可以这样做:

select customer, order from Customer customer, Order order 
    where order.CustomerID = customer.Id
    and customer.Id = 42

然后,结果集将是一个 object[] 列表,其中客户将重复多次他下的订单数(当然假设有一个客户对多个订单)。

请注意,如果没有任何订单,结果将为空。

于 2009-02-05T11:36:27.440 回答
1

如果您不想或无法在实体中定义关联属性(例如在支持插件动态加载的模块化应用程序中),您仍然可以使用 Fluent api 创建“假”关联。

请参阅 Orchard 源代码,“ContentItemAlteration”类。在 Orchard 中,希望将 ContentItem 实体与存储在不同表中的 ContentPart 记录连接起来。每个 ContentPart 类型都由模块提供,这意味着很难(并且可能不是首选)更改 ContentItem 的源并为每个新部分记录添加关联。

这是我从 Orchard 来源获得的确切代码:

/// <summary>
    /// Add a "fake" column to the automapping record so that the column can be
    /// referenced when building joins accross content item record tables.
    /// <typeparam name="TItemRecord">Either ContentItemRecord or ContentItemVersionRecord</typeparam>
    /// <typeparam name="TPartRecord">A part record (deriving from TItemRecord)</typeparam>
    /// </summary>
    class Alteration<TItemRecord, TPartRecord> : IAlteration<TItemRecord> {
        public void Override(AutoMapping<TItemRecord> mapping) {

            // public TPartRecord TPartRecord {get;set;}
            var name = typeof(TPartRecord).Name;
            var dynamicMethod = new DynamicMethod(name, typeof(TPartRecord), null, typeof(TItemRecord));
            var syntheticMethod = new SyntheticMethodInfo(dynamicMethod, typeof(TItemRecord));
            var syntheticProperty = new SyntheticPropertyInfo(syntheticMethod);

            // record => record.TPartRecord
            var parameter = Expression.Parameter(typeof(TItemRecord), "record");
            var syntheticExpression = (Expression<Func<TItemRecord, TPartRecord>>)Expression.Lambda(
                typeof(Func<TItemRecord, TPartRecord>),
                Expression.Property(parameter, syntheticProperty),
                parameter);

            mapping.References(syntheticExpression)
                .Access.NoOp()
                .Column("Id")
                .ForeignKey("none") // prevent foreign key constraint from ContentItem(Version)Record to TPartRecord
                .Unique()
                .Not.Insert()
                .Not.Update()
                .Cascade.All();
        }
    }

此代码只是向 ContentItem 添加了一个“部分”关联,使您能够在您的条件中使用连接。例如,如果您有一个名为“ProductPart”的部件存储在一个名为“ProductPartRecord”的表中,那么您可以在假属性“ProductPartRecord”上加入您的 ContentItem。

By the way, it seems this tactic can also be applied to HasMany side of the fake relation but you have to customize the Fluent sources I suppose.

于 2012-11-21T23:08:39.120 回答