c#


NHibernate How do i put data in many to many mapping


These are my two classes. I did the mapping and the configuration.
Please instruct me how do I put data into this.
class Actor
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual IList <Movies> Movie{ get; set; }
}
class Movies
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual IList <Actor> Actors{ get; set; }
}
I'm not sure what exactly you are asking here, but I'll try to answer what I think you are asking.
In order to map a many-to-many relationship to the database with Fluent NHibernate for the classes in your question would be as simple as
public class ActorMap : ClassMap<Actor>
{
public ActorMap()
{
Id(x => x.Id);
Map(x => x.Name);
HasManyToMany(x => x.Movies)
.Table("Actors_Movies")
.ParentKeyColumn("ActorId")
.ChildKeyColumn("MovieId")
.LazyLoad()
.Cascade.AllDeleteOrphan();
}
}
public class MovieMap : ClassMap<Movie>
{
public MovieMap()
{
Id(x => x.Id);
Map(x => x.Name);
HasManyToMany(x => x.Actors)
.Table("Actors_Movies")
.ParentKeyColumn("ActorId")
.ChildKeyColumn("MovieId")
.Inverse();
}
}
The junction table in the database is transparent to the relationship in code; consider this an artifact of the impedance mismatch of mapping object oriented code to a relational database.
Now, if you needed to store additional data against the junction table, you would need to expose a type in code to represent the junction table, and add properties to this type for the data you wish to store
public class MovieActorAssociation
{
public MovieActorAssociation(Actor actor, Movie movie)
{
Actor = actor;
Movie = movie;
}
protected MovieActorAssociation()
{
}
public virtual Actor Actor { get; protected set; }
public virtual int Id { get; protected set; }
public virtual Movie Movie { get; protected set; }
public virtual string SomeOtherProperty { get; set; }
public static bool operator ==(MovieActorAssociation left, MovieActorAssociation right)
{
return Equals(left, right);
}
public static bool operator !=(MovieActorAssociation left, MovieActorAssociation right)
{
return !Equals(left, right);
}
public override bool Equals(object obj)
{
if (ReferenceEquals(null, obj))
{
return false;
}
if (ReferenceEquals(this, obj))
{
return true;
}
if (obj.GetType() != GetType())
{
return false;
}
return Equals((MovieActorAssociation)obj);
}
public override int GetHashCode()
{
return Id;
}
protected bool Equals(MovieActorAssociation other)
{
return Id == other.Id;
}
}
Now, to map the relationship
public class ActorMap : ClassMap<Actor>
{
public ActorMap()
{
Id(x => x.Id).GeneratedBy.Identity();
Map(x => x.Name);
HasMany(x => x.MovieAssociations)
.Cascade.AllDeleteOrphan()
.Inverse()
.KeyColumn("ActorId")
.Not.KeyNullable();
}
}
public class MovieActorAssociationMap : ClassMap<MovieActorAssociation>
{
public MovieActorAssociationMap()
{
Id(x => x.Id).GeneratedBy.Identity();
Map(x => x.SomeOtherProperty);
References(x => x.Movie)
.Not.Nullable()
.Cascade.SaveUpdate()
.Column("MovieId")
.UniqueKey("Movie_Actor");
References(x => x.Actor)
.Not.Nullable()
.Cascade.SaveUpdate()
.Column("ActorId")
.UniqueKey("Movie_Actor");
}
}
public class MovieMap : ClassMap<Movie>
{
public MovieMap()
{
Id(x => x.Id).GeneratedBy.Identity();
Map(x => x.Name);
HasMany(x => x.ActorAssociations)
.Cascade.AllDeleteOrphan()
.Inverse()
.KeyColumn("MovieId")
.Not.KeyNullable();
}
}
And to use
var actor = new Actor { Name = "Actor Name" };
var movie = new Movie { Name = "Movie Name" };
var association = new MovieActorAssociation(actor, movie);
actor.MovieAssociations.Add(association);
movie.ActorAssociations.Add(association);
// some way of getting a Session
var session = SessionFactory.GetCurrentSession();
using (var transaction = session.BeginTransaction())
{
session.Save(actor);
transaction.Commit();
}
You may want to consider exposing methods for adding and removing MovieActorAssociation types to ensure association correctness i.e. that an association added to the property collection on an Actor references the Actor instance that owns the collection and not another actor instance. You would want similar logic to this for Movie types too.

Related Links

Conditional Compile of Generic Methods
VS WinForm designer always changes custom constructor?
Run C# application from cmd
Knowing the status of a very long function (execution time) in another class [closed]
Add a single row containing text taking up entire area of WPF Datagrid
CGBitmapContext in MonoTouch throws invalid handle exception
Create a list to display the contents of a dictionary?
Get file to FileStream from remote path with another user credentials
Implementing the min & max function with group by and having in linq
JSON or HTML returned from webmethod
BackgroundWorker doesn't handle exception
Implementing C++/clr's auto_handle functionality in C#
Get Children from ListBox can't get children that haven't been viewed
DelegatingHandler for response in WebApi
MVC4 bundling CSS failed Unexpected token, found '#import'
What's the correct way to deal with Try/Catch Blocks and Errors in General when using multiple classes?

Categories

HOME
spring-boot
url
itunesconnect
netty
compression
ibm
nagios
postsharp
spss
lithium
query-string
coordinates
download
confluence-rest-api
checkpoint
comments
opacity
procmon
ng2-charts
opengrok
exchange-transport-agents
taxonomy
internet-explorer-7
md2
gpo
spring-webflow
url-parameters
vala
opengraph
procedural-generation
typeclass
spring-data-gemfire
folder
paper-trail-gem
overflow
loopback
jcr
luhn
abide
motion
compiled-query
aspnetboilerplate
web-technologies
weld
hierarchical-clustering
runner
emacs24
dcom
multivalue
seyren
webmatrix
petapoco
overhead
google-scholar
blitz3d
indoor-positioning-system
jigsaw
python-rq
calc
instabug
dday
dynamics-nav
php-gd
redquerybuilder
uinavigationitem
consul-template
pagecontrol
firewire
page-refresh
glog
system.diagnostics
radgrid
jad
chunks
esri-arc-engine
fxmlloader
parallel-port
winrun4j
pidgin
fastcgi-mono-server
node-mongodb-native
nvcc
carrier
xml-validation
cab
azure-pack
forward-declaration
azure-scheduler
pudb
system.transactions
blotter
quit
m3u
google-email-audit-api
winrt-async
django-admin-tools
code-organization
umfpack
jquery-click-event
object-tag
cinder
xcdatamodel
virtual-destructor
nyromodal
dgml
mdd
morfik
file-storage
scala-designer
projectgen
j++

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App