开发者

NHibernate 1:n mapping to 1:1 with restrictions

开发者 https://www.devze.com 2023-03-26 05:37 出处:网络
I have my application liek this: I have a class Product I have user track this product, so class Track 开发者_JS百科

I have my application liek this:

  1. I have a class Product
  2. I have user track this product, so class Track
开发者_JS百科

Note multiple user can track one product, so the relationship between Product : Track is 1 : n

However, if user is currently signed in, it can only be 1 Track associated to Product, and in my list page, I should display a list of products with its track status for current user, something like:

  • Product A - Tracked on 2011-01-01
  • Product B - Not Tracked
  • Product C - Tracked on 2010-12-20
  • ...

Thus in plain sql, I may have a query like this:

select * from Product as p 
left outer join Track as t 
    on t.ProductId = p.Id and t.UserId = {currentUser.Id}

But using NHibernate I find it not easy to implement, currently I have a ProductWithTrack class, which inherits from Product class and adds a Track property:

class ProductWithTrack : Product {
    public Track Track { get; set; }
}

My effort is to map this class to Product table just the same as Product class, but how can I figure the mapping of Track property, I have tried:

  • one-to-many, but Track is not a collection
  • many-to-one / one-to-one, this requires a foreign key column in Product table which certainly not exists

Please help in this mapping problem, thanks.


One approach is based on the observation that the list page is a reporting view of the data. In particular it combines information about products and their tracking status. For a reporting view, you don't need to create an explicit mapping for the desired data, instead you can use the query capabilities of NHibernate and possibly projections to get the results you need. In other words, ProductWithTrack does not need to be its own entity.

As another approach, instead of having ProductWithTrack inheriting from Product you should have a class called TrackedProduct:

class TrackedProduct {
 public int ID { get; private set; }
 public Product Product { get; private set; }
 public Track Track { get; private set; }
}

This class represents the concept of a tracked product and has its own identity. You can then query this entity to get the desired data.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号