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

How to keep the original document when projecting in mongodb?
Use split to remove parts of a string that are surrounded by curly double quotes
Installing json.net via NU get error 'Newtonsoft.Json' already has a dependency defined for Microsoft C#
Only insert data into a database if it doesn't exist already
Entity Framework not Finding Table
Windows Service Communicate WIth UI
How can I prevent screen recording using C#?
Angular $http.post() to C# Web API Controller
Return parameter in controller instead a View
How can I pause the audio source and animation at the same time in unity 3d
When should I use ServiceFabricIntegrationOptions.UseUniqueServiceUrl
Regex match and replace operators in math operation
ASP.NET login web application on intranet against Active Directory Domain
Why is the hub context connection ID inaccessible at runtime in my VERY simple method?
How to prevent the CSharpCodeProvider to output access modifiers
How can I get the value of a radio button when the page is posted with mvc

Categories

HOME
pact
oop
swift3
system-calls
domain-driven-design
grpc
msbi
foreach
atlassian-fisheye
aggregate-functions
markdown
handlebars.js
scapy
ejb-3.0
openbsd
solidity
jetbrains
hdf5
oxid
react-select
box2d
background-image
jsfiddle
geography
aws-devicefarm
gpo
openoffice-basic
minimagick
restructuredtext
handle
hierarchical-data
boosting
osgi-bundle
ipython-parallel
wordpress-rest-api
odp.net
azure-vm-scale-set
mkdir
kofax
android-databinding
anypoint-studio
form-fields
yelp
jquery-inputmask
jslider
julia-jump
fisheye
keychain
android-graphview
php-mongodb
gradlew
togglebutton
activeandroid
google-chrome-storage
dcom
openxava
multivalue
vertex
perldoc
openpgp.js
seyren
hellosign
selection-sort
scanf
android-tabs
disconnect
user-profile
nugetgallery
fadein
nslocalizedstring
instabug
jquery-draggable
android-contentresolver
jain-sip
om
openhab
autoscaling
callfire
xml-simple
system.diagnostics
diffmerge
vundle
ios-enterprise
time-frequency
twitter-finagle
banana-pi
connections
mdp
vbaccelerator
mysql-error-1146
kendo-window
ironworker
static-class
dd4t
cocotron
architectural-patterns
rbm
event-propagation
filedialog
win-prolog
jqueryi-ui-buttonset
inserthtml
scriptmanager
designated-initializer
nbehave
numerical-computing
pkcs#7
file-storage
ffdshow

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