How to map it? HasOne x References

2019-03-04 01:27发布

I need to make a mapping One by One, and I have some doubts. I have this classes:

public class DocumentType {    
    public virtual int Id { get; set; }    
    /* othes properties for documenttype */  
    public virtual DocumentConfiguration Configuration { get; set; }
    public DocumentType () { } 
}

public class DocumentConfiguration {
   public virtual int Id { get; set; }
   /* some other properties for configuration */   
   public virtual DocumentType Type { get; set; }

  public DocumentConfiguration () { }
}

A DocumentType object has only one DocumentConfiguration, but it is not a inherits, it's only one by one and unique, to separate properties.

How should be my mappings in this case ? Should I use References or HasOne ? Someone could give an example ?

When I load a DocumentType object I'd like to auto load the property Configuration (in documentType).

Thanks a lot guys!

Cheers

2条回答
狗以群分
2楼-- · 2019-03-04 01:52

Even though you have a one-to-one in your domain, your relational model is probably one-to-many. I doubt you share same PK on both tables, more likely you have FK on DocumentConfiguration for DocumentType. In that case you would map it as such, because what you are mapping is your relational model. So on DocumentType it would be HasOne.Inverse.AllDeleteOrphan ... and on DocumentConfiguration it would be "References".

Now you domain should expose it as you are describing it.

public class DocumentConfiguration 
{
    public DocumentConfiguration() 
    {
        _internalDocumentConfigurations = new List<DocumentConfiguration>(1);
    }  

   private IList<DocumentConfiguration> _internalDocumentConfigurations
   public virtual DocumentType Type 
   { 
     get 
     { 
        return _internalDocumentConfigurations.FirstOrDefault();
     } 
     /**/WARNING - no setter here**
   }
   public virtual SetDocumentConfiguration(DocumentConfiguration config)
   {
      //add your asserts here
      Add(config);
   }

   private virtual Add (DocumentConfiguration config)
   {
     //add your asserts here
      _internalDocumentConfigurations.Add(config)
       config.DocumentType = this;
   }

  public virtual Remove (DocumentConfiguration config)
  {
      _internalDocumentConfigurations.Remove(config)
      config.DocumentType = null;
  }

}

public class DocumentConfiguration {
   public virtual int Id { get; set; }
   /* some other properties for configuration */   
   public virtual DocumentType Type { get;  protected internal set; }
查看更多
3楼-- · 2019-03-04 01:57

If the relationship is really one-to-one... then use HasOne :-)

See http://nhibernate.info/doc/nhibernate-reference/mapping.html#mapping-declaration-onetoone. It has all you need to know.

查看更多
登录 后发表回答