Fluent NHibernate join for property value

依然范特西╮ 提交于 2019-12-13 05:44:33

问题


I'm trying to join a table to retreive and set a property on a POCO. Here's the scenario...

*NOTE - An application can belong to many user sessions.

UserSession (Table)

UserSessionId PK
ApplicationId FK
UserName

Application (Table)

ApplicationId PK
Name

UserSession (Poco)

string UserName get;
string ApplicationName get;

I've tried a join like this:

Join("Application", j => j.Inverse().KeyColumn("ApplicationId").Map(x => x.ApplicationName));

However, this uses the primary column of the UserSessionTable for the join column. The part of the query looks like this:

/**SNIP**/
inner join
 Auditing.UserSession US
     on this_.UserSessionId=US.UserSessionId
left outer join
 Auditing.Application A
     on US.UserSessionId=A.ApplicationId
/**SNIP**/

How can i configure nhibernate fluently to use the correct join column from the left table(UserSession)?


回答1:


If you would manage to map this UserSession class, it would have side effects. Consider this code:

// assume that both user sessions share the same Application.
UserSession userSession1 = session.Get<UserSession>(1);
UserSession userSession2 = session.Get<UserSession>(2);

// what should happen here?
userSession1.ApplicationName = "Blah";

You may not want to change the application name in your code. However, the ORM needs to synchronize data always in both directions to make sense.

You could fix the problem by actually map it as it is in the database, say by making the application a real entity.

class UserSession
{
  Application Application { get; private set; }
}

If this structure is too complicated for your case, consider to write a query which returns the data as you need:

select session.Name, application.Name
from UserSession session join Application

You could also create a new structure from the query (select new ...). Also take a look at named queries.




回答2:


Joe unfortunately I don't think you can specify this column. I believe this is an nhibernate limitation (not FluentNH). There are workarounds to this. Here is an article with the same type of question:

Fluent NHibernate join tables in mapping not using primary key

Edit:
Example using your new entity below:

References(x => x.Application, "ApplicationId")

This allows you to specify the column on which you are joining to the Application table.



来源:https://stackoverflow.com/questions/6031630/fluent-nhibernate-join-for-property-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!