流利的NHibernate - 将一个属性映射到一个连接表上的列 [英] Fluent NHibernate - Mapping a property to a column on a joined table
问题描述
- 产品{Id,Name,ManufacturerId,...} li>
- 制造商{Id,Name,...}
我希望能够在我的Product对象中包含ManufacturerName(而不必在我只需要名称时加载整个Manufacturer行)。我的ProductMap看起来像...
表(Product);
Id(x => x.Id,Id);
Map(x => x.ProductName,ProductName);
Map(x => x.ManufacturerId,ManufacturerId);
参考文献(x => x.Manufacturer,ManufacturerId);
我需要添加什么来填充我的Product对象的ManufacturerName属性?我相信我需要做一些Join()调用,但是我很难弄清楚如何用所有相关的参数来编写它。它需要加入当前表(产品)到制造商表,在Product.ManufacturerId = Manufacturer.Id,并抓住Manufacturer.Name列,填充对象的ManufacturerName属性。
$ b $ ol
添加一个将该新属性的行映射到您的ProductMap中:
Table(Product);
Id(x => x.Id,Id);
Map(x => x.ProductName,ProductName);
Map(x => x.ManufacturerId,ManufacturerId);
Map(x => x.ManufacturerName).Formula((m.ManufacturerName from Manufacturer m where m.Id = ManufacturerId));
参考文献(x => x.Manufacturer,ManufacturerId);
希望这有帮助。 b $ b
I've got a couple tables, for example:
- Product {Id, Name, ManufacturerId, ...}
- Manufacturer {Id, Name, ...}
I'd like to be able to include ManufacturerName on my Product object (instead of having to load the whole Manufacturer row when I only need the name). My ProductMap looks like...
Table("Product");
Id(x => x.Id, "Id");
Map(x => x.ProductName, "ProductName");
Map(x => x.ManufacturerId, "ManufacturerId");
References(x => x.Manufacturer, "ManufacturerId");
What do I need to add to populate the ManufacturerName property on my Product object? I believe I need to make some sort of Join() call, but I'm having trouble figuring out how to write it with all the relevant parameters. It needs to join the current table (Product) to the Manufacturer table, on Product.ManufacturerId = Manufacturer.Id, and grab the Manufacturer.Name column, populating the ManufacturerName property on the object.
I think you could use a formula
to dynamically retrieve a manufacturer name. This is not an elegant solution and personally I would prefer using a separate sql view mapped to a new entity (e.g. ProductExtra, etc.) where it would query just necessary columns but anyways. Here we go:
- Add the ManufacturerName property to the Product class
Add a mapping line for that new property to your ProductMap:
Table("Product"); Id(x => x.Id, "Id"); Map(x => x.ProductName, "ProductName"); Map(x => x.ManufacturerId, "ManufacturerId"); Map(x => x.ManufacturerName).Formula("(select m.ManufacturerName from Manufacturer m where m.Id = ManufacturerId)"); References(x => x.Manufacturer, "ManufacturerId");
Hope this helps.
这篇关于流利的NHibernate - 将一个属性映射到一个连接表上的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!