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

using checkbox to enable textbox
Why are Anchor properties not being honored within dynamically created nested components?
Dataset data is different that stored procedure
Zip file being accessed by multiple user - Mem out of exception issue
Why I can't use FileStream in windows store app [duplicate]
Save file to server viaWCF
T4 runtime template path specification
JSON.NET CustomCreationConverter with nested objects
Can a C# Interface require or dictate a specific class?
MySQL Query Doesn't Return Value, But Exists In DB
Comparing user input username/password to mysql database username/password not working
MvxException: Failed to resolve type…IRepository
Stop geolocation service windows phone 8
Multidimensional array init without pre-existing values?
StreamReader OutOfMemoryException [closed]
Dynamically Create Draggable UserControl in Win8 Metro App

Categories

HOME
drupal
msbuild
swift3
ftp
glsl
postsharp
gaussian
jquery-plugins
stdout
artifactory
thermal-printer
perl6
css-selectors
uml-designer
servicenow
travis-ci-cli
wavefront
gcloud
websharper
tmux
aggregate
infopath
smooth-scrolling
ofbiz
xforms
caldav
jq
descriptor
restructuredtext
ecmascript-2017
chartist.js
oracle10g
knapsack-problem
symlink
spring-data-gemfire
openoffice-impress
jql
microstrategy
incapsula
android-geofence
mkdir
const
jquery-inputmask
mediastream
susy
jvisualvm
ape-phylo
contenteditable
bootstrap-carousel
django-cors-headers
togglebutton
line-endings
hdpi
jscoverage
grib
racket-student-languages
consolidation
hoare-logic
git-cherry-pick
sbt-proguard
audiorecord
bbedit
video-embedding
skbio
apache2-module
google-app-engine-php
web-performance
transport
self-join
firewire
vspackage
jeet-grid
valdr-bean-validation
asp.net-2.0
mri
attiny
shunting-yard
fiware-health
drools-guvnor
random-access
uiblureffect
react-os
yosemite
zoneminder
parsefloat
nsmutableurlrequest
visual-studio-setup-proje
cvi
maven-javadoc-plugin
ardor3d
grape-api
static-class
oc4j
pyxplot
leap-year
netbiscuits
doxia
pdf-reader
django-admin-tools
pinchzoom
cgaffinetransform
recess
overlays
jquery-click-event
hwnd
meego-harmattan
lwp
excellibrary
nyromodal
simultaneous
table-valued-parameters
web-search
file-storage
zend-acl
onresize
cstring
vista64

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