NHibernate. Join unrelated entities

后端 未结 3 2074
自闭症患者
自闭症患者 2021-01-22 16:34

Is there any way to execute following query with native NHibernate linq provider?

var result =
    (from e1 in Session.Query()
     join e2 in Se         


        
相关标签:
3条回答
  • 2021-01-22 17:16

    Not using LINQ, but you can do theta joins when using HQL.

    Select e1.Id, e1.SomeField, e2.SomeUnrelatedField 
    from Entity1 e1, Entity2 e2  where e1.SomeField = e2.SomeField
    

    However, you won't be able to do outer joins with this. So if that's a requirement, you'll have to go with raw SQL.

    0 讨论(0)
  • 2021-01-22 17:18

    It's still not supported.

    You should either introduce a relation between the objects or use SQL for the query.

    0 讨论(0)
  • 2021-01-22 17:24

    I'm not quite sure when this was introduced but this is now supported by NHibernate. I am using version 3.3.1 and I have a query very similar to yours working well. The test below works for me:

    [TestFixture]
    public class NHibernateJoinUnrelatedEntitiesTest
    {
        private ISessionFactory sessionFactory;
    
        [Test]
        public void I_Can_Join_Unrelated_Entities()
        {
            // Arrange
            ISession session = sessionFactory.OpenSession();
    
            // Act
            var results = (
                              from c in session.Query<Customer>()
                              from wal in session.Query<WebsiteActivityLog>()
                              where c.Id == wal.CustomerId
                                    && c.Id == 54856
                              select new { CustomerId = c.Id, Name = c.FirstName, Address = wal.IpAddress }
                          ).ToList();
    
            // Assert
            Assert.NotNull( results );
        }
    
        public class Customer
        {
            public virtual int Id { get; set; }
            public virtual string FirstName { get; set; }
        }
    
        public class WebsiteActivityLog
        {
            public virtual int Id { get; set; }
            public virtual int CustomerId { get; set; }
            public virtual string IpAddress { get; set; }
        }
    
        public class CustomerMap : ClassMap<Customer>
        {
            public CustomerMap()
            {
                Id( x => x.Id );
                Map( x => x.FirstName );
            }
        }
    
        public class WebsiteActivityLogMap : ClassMap<WebsiteActivityLog>
        {
            public WebsiteActivityLogMap()
            {
                Id( x => x.Id );
                Map( x => x.CustomerId );
                Map( x => x.IpAddress );
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题