I'm trying to learn NHibernate 3.2 built-in mapping by code api
(NOT FluentNHibernate, nor xml). Can you help me to map a many-to-many relationship between these entities please?
public class Post {
public virtual Id { get; set; }
public IList<Tag> Tags { get; set; }
}
public class Tag {
public virtual Id { get; set; }
public IList<Post> Posts { get; set; }
}
My primary key strategy is:
Id(
t => t.Id,
t => {
t.Generator(Generators.HighLow, g => g.Params(new { max_low = 100 }));
t.Column(typeof(TEntity).Name + "Id");
});
and I try this:
// TagMap : ClassMapping<Tag>
Bag(t => t.Posts, bag => {
bag.Inverse(true);
bag.Table("TagsPosts");
bag.Cascade(Cascade.DeleteOrphans);
}, t => t.ManyToMany(c => {
c.Column("PostId");
c.Lazy(LazyRelation.Proxy);
}));
// PostMap : ClassMapping<Post>
Bag(t => t.Tags, bag => {
bag.Table("TagsPosts");
bag.Cascade(Cascade.DeleteOrphans);
}, t => t.ManyToMany(c => {
c.Column("TagId");
c.Lazy(LazyRelation.Proxy);
}));
but it doesn't work.
This includes the NHibernate.Mapping.Attributes library which allows to directly annotate your entities with mapping declarations, various template-based code generators (CodeSmith, MyGeneration), the built-in NHibernate.Mapping.ByCode API available since NHibernate 3.2, or the Fluent NHibernate independent library.
entity-name (optional - defaults to the class name): NHibernate allows a class to be mapped multiple times, potentially to different tables. See Section 5.3, “Mapping a class more than once” . It also allows entity mappings that are represented by dictionaries at the .Net level.
If you have two persistent classes with the same (unqualified) name, you should set auto-import="false". NHibernate will throw an exception if you attempt to assign two classes to the same "imported" name.
In other words, the instance will be updated. undefined does not assume anything: NHibernate may query the database for determining if the entity is already persisted or not. mapped (optional - defaults to false ): This attribute has no usage in NHibernate.
// Post Map
Bag(x => x.Tags, collectionMapping =>
{
collectionMapping.Table("TagPosts");
collectionMapping.Cascade(Cascade.None);
collectionMapping.Key(k => k.Column("PostID"));
},
map => map.ManyToMany(p => p.Column("TagID")));
// Tag Map
Bag(x => x.Posts, collectionMapping =>
{
collectionMapping.Table("TagPosts");
collectionMapping.Cascade(Cascade.None);
collectionMapping.Key(k => k.Column("TagID"));
},
map => map.ManyToMany(p => p.Column("PostID")));
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