Save a Child for a existent Parent

梦想与她 提交于 2019-12-24 08:49:01

问题


I have a model with some inherits and it is using nhibernate to persisti on a Database. The nhibernate mapping with fluent nhibernate is working fine, but I have a scenario where I need to save a child for a existent parent. My model looks like this:

public class Item
{
   public long Id { get; set; }
   public string Name { get; set; }
   // other properties
}

public class ItemCommercial : Item
{
   public decimal Value { get; set; }
   // other properties
} 

In my Database, the respective tables are related by Id <-> Id (one per one).

I would like to know, how to Save just a ItemCommercial instance for a existent Item on database. I have the Id of the Item, but I do not know howt to say to nhibernate to say just the Child, instead creating a new Item, for sample:

session.Save(itemCommercialObj); // will create a Item and ItemCommercial with the same Id

Thank you.


回答1:


As I also answered here

No, it is not possible to "upgrade" an already persisted object to its subclass. Nhibernate simply doesn't support this. If you safe the subclass with the same ID as the base class, Nhibernate simply creates a copy with a new ID of the object instead of creating the reference to Member...

So basically you could do either

  1. Copy the data of Customer into Member, delete customer and save Member
  2. Use a different object structure without subclasses where Member is a different table with it's own ID and a reference to Customer
  3. Use native sql to insert the row into Member...



回答2:


you can not the runtimetype of an object like that hence NH does not support it. Change the design to

public class Item
{
    public long Id { get; set; }
    public string Name { get; set; }
    public CommercialValue CommercialValue { get; set; }
    // other properties
}

public class CommercialValue
{
    public Item Item { get; set; }
    public decimal Value { get; set; }
    // other properties
}

and a one-to-one mapping. Then it is as simple as setting the CommercialValue property



来源:https://stackoverflow.com/questions/17726679/save-a-child-for-a-existent-parent

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