code_junkie

Fluent NHibernate: How to create one-to-many bidirectional mapping?

Nov 12th, 2011
56
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.75 KB | None | 0 0
  1. public class Summary
  2. {
  3. public int id {get; protected set;}
  4.  
  5. public IList<Detail> Details {get; protected set;}
  6. }
  7.  
  8. public class Detail
  9. {
  10. public int id {get; protected set;}
  11.  
  12. public string ItemName {get; set;}
  13.  
  14. /* public Summary Owner {get; protected set;} */ //I think this might be needed for bidirectional mapping?
  15. }
  16.  
  17. public class SummaryMap : ClassMap<Summary>
  18. {
  19. public SummaryMap()
  20. {
  21. Id(x => x.ID);
  22.  
  23. HasMany<Detail>(x => x.Details);
  24. }
  25. }
  26.  
  27. public class DetailMap : ClassMap<Detail>
  28. {
  29. public DetailMap()
  30. {
  31. Id(x => x.ID);
  32.  
  33. Map(x => x.ItemName).CanNotBeNull();
  34. }
  35. }
  36.  
  37. public class Detail
  38. {
  39. public int id { get; protected set; }
  40. public string ItemName { get; set; }
  41.  
  42. // Renamed to use same column name as specified in the mapping of Summary.Details
  43. public Summary Summary {get; set;}
  44. }
  45.  
  46. public class Summary
  47. {
  48. public Summary()
  49. {
  50. Details = new List<Detail>();
  51. }
  52.  
  53. public int id { get; protected set; }
  54. public IList<Detail> Details { get; protected set; }
  55. }
  56.  
  57. public class DetailMap : ClassMap<Detail>
  58. {
  59. public DetailMap()
  60. {
  61. Id(x => x.id)
  62. .GeneratedBy.Native();
  63.  
  64. Map(x => x.ItemName)
  65. .CanNotBeNull();
  66.  
  67. References<Summary>(x => x.Summary)
  68. // If you don't want to rename the property in Summary,
  69. // you can do this instead:
  70. // .TheColumnNameIs("Summary_id")
  71. .CanNotBeNull();
  72. }
  73. }
  74.  
  75. public class SummaryMap : ClassMap<Summary>
  76. {
  77. public SummaryMap()
  78. {
  79. Id(x => x.id)
  80. .GeneratedBy.Increment();
  81.  
  82. HasMany<Detail>(x => x.Details)
  83. .IsInverse()
  84. .AsBag(); // Use bag instead of list to avoid index updating issues
  85. }
  86. }
Add Comment
Please, Sign In to add comment