For a (very) long time I've been looking for an example on how to correctly implement a one-to-one mapping with Fluent NHibernate.
Most resources I find say:
I think you mean a many-to-one
However no one actually gives an example on how to correctly implement the one-to-one relation.
So, could you give an one-to-one mapping example with Fluent NHibernate?
Note: I'm not interested in people saying "what's your model, you might actually need HasMany". No, thanks, I simply need a one-to-one example.
To be more precise, I know the syntax. That's the only thing I could find by searching by myself. What I'm looking for is a more complete example, including a ((very) simple) database setup, and the whole mapping, of all entities that participate in the relationship, which I think would have reasonable size for Stack Overflow.
Fluent NHibernate offers an alternative to NHibernate's standard XML mapping files. Rather than writing XML documents, you write mappings in strongly typed C# code. This allows for easy refactoring, improved readability and more concise code.
NHibernate is the ORM, an object-relational platform that works on the ASP.Net core. Therefore, we can easily deploy the core project developed in ASP.NET that uses NHibernate on the Linux server without any effort. The application works in the same way as it will do on a windows platform.
NHibernate is an ORM (Object Relational Mapper). Its purpose is to map objects in your OO application to tables in a database for persistence. Why would you need it? Because it can save you from writing a lot of tedious ADO.NET code.
I've solved my problem.
I've also written a somewhat detailed article on this problem, that you can find at: http://brunoreis.com/tech/fluent-nhibernate-hasone-how-implement-one-to-one-relationship/index.html
You will find a scenario in which we want a one-to-one relationship, the database schema as we would like it, the code of the model as it needs to be to meet NHibernate requirements, and the Fluent mapping that corresponds to the situation.
these are the two classes. public class A { public virtual int Id {get;set;} public virtual string P1 {get;set;} public virtual string P2 {get;set;} public virtual string P3 {get;set;} public virtual B child { get; set; } } public class B { public virtual int Id {get;set;} public virtual string P4 {get;set;} public virtual string P5 {get;set;} public virtual string P6 {get;set;} public virtual A parent; }
this should be added in the fluent configuration.
public AMap() { /* mapping for id and properties here */ HasOne(x => x.child) .Cascade.All(); } public BMap() { /* mapping for id and properties here */ References(x => x.parent) .Unique(); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With