Fluent NHibernate Dictionary mapping problem - fluent-nhibernate

I have following entities
public class Entity1
{
public virtual Guid Id { get; set; }
public virtual IDictionary<Guid, Entity2> Entities2 { get; set; }
}
public class Entity2
{
public virtual Guid Id { get; set; }
public virtual IDictionary<Guid, Entity1> Entities1 { get; set; }
}
DB table
CREATE TABLE [dbo].[EntityLinks](
[Entity1Id] [uniqueidentifier] NOT NULL,
[Entity2Id] [uniqueidentifier] NOT NULL,
[LinkItemId] [uniqueidentifier] NOT NULL
)
and following mappings:
for Entity1
mapping.HasManyToMany<Entity2>(rc => rc.Entities2)
.Table("EntityLinks")
.ParentKeyColumn("Entity1Id")
.ChildKeyColumn("Entity2Id")
.AsMap<Guid>("LinkItemId")
for Entity2
mapping.HasManyToMany<Entity1>(rc => rc.Entities1)
.Table("EntityLinks")
.ParentKeyColumn("Entity2Id")
.ChildKeyColumn("Entity1Id")
.AsMap<Guid>("LinkItemId")
adding data works fine and I can get and see Entity1.Entities2 populated but Entity2.Entities1 is not populated.
Any suggestions why this might be?
Thank you in advance.

I'm probably wrong but you can try:
mapping.HasManyToMany<Entity2>(rc => rc.Entities2)
.Table("EntityLinks")
.ParentKeyColumn("Entity1Id")
.ChildKeyColumn("Entity2Id")
.AsMap<Guid>("LinkItemId")
.Inverse()
and
mapping.HasManyToMany<Entity1>(rc => rc.Entities1)
.Table("EntityLinks")
.ParentKeyColumn("Entity2Id")
.ChildKeyColumn("Entity1Id")
.AsMap<Guid>("LinkItemId")
.Cascade.All();

Related

Fluent NHibernate Mapping for Table in multiple HasMany Relationships

What is wrong with my class mappings below?
public class Foo
{
public Foo()
{
ActualCurve = new List<Point>();
TargetCurve = new List<Point>();
}
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual IList<Point> ActualCurve { get; set; }
public virtual IList<Point> TargetCurve { get; set; }
}
public class Point
{
public virtual int Id { get; set; }
public virtual double X { get; set; }
public virtual double Y { get; set; }
}
public class FooMapping() : ClassMap<Foo>
{
Table("Foos");
Id(x => x.Id).GeneratedBy.Identity();
Map(x => x.Name).Not.Nullable();
HasMany(x => x.ActualCurve ).Cascade.All();
HasMany(x => x.TargetCurve ).Cascade.All();
}
public class PointMapping() : ClassMap<Point>
{
Table("Points");
Not.LazyLoad();
Id(x => x.Id).GeneratedBy.Identity();
Map(x => x.X).Not.Nullable();
Map(x => x.Y).Not.Nullable();
}
These mappings produce
CREATE TABLE [dbo].[Foos](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar] NOT NULL,
[RecipeRevisionId] [int] NOT NULL
CREATE TABLE [dbo].[Points](
[Id] [int] IDENTITY(1,1) NOT NULL,
[X] [float] NOT NULL,
[Y] [float] NOT NULL,
[FooId] [int] NOT NULL
Essentially, the problem is that when I am pulling a persisted Foo object back out of the database, the Foo.ActualCurve and Foo.TargetCurve lists both get populated with the combined contents of both lists. There clearly isn't a column that keys which set of points belong to the correct curve within Foo, but I am not sure how to change the mapping to maintain the two distinct sets of Points.
I think you will need to specify a separate column for the references:
HasMany(x => x.ActualCurve ).Cascade.All().KeyColumn("ActualCurveId");
HasMany(x => x.TargetCurve ).Cascade.All().KeyColumn("TargetCurveId");
EDIT: Column->KeyColumn

Using References (many-to-one) in Fluent NHibernate creates a Foreign Key in both ends, the many end and the one-end

as the title says, I would like to create a many-to-one relationship using Fluent NHibernate. There are GroupEntries, which belong to a Group. The Group itself can have another Group as its parent.
These are my entities:
public class GroupEnty : IGroupEnty
{
public virtual long Id { get; set; }
public virtual string Name { get; set; }
...
public virtual IGroup Group { get; set; }
}
public class Group : IGroup
{
public virtual long Id { get; set; }
public virtual string Name { get; set; }
...
public virtual IGroup Parent { get; set; }
}
And these are the mapping files:
public class GroupEntryMap : ClassMap<GroupEntry>
{
public GroupEntryMap()
{
Table(TableNames.GroupEntry);
Id(x => x.Id).GeneratedBy.Native();
Map(x => x.Name).Not.Nullable();
...
References<Group>(x => x.Group);
}
}
public class GroupMap : ClassMap<Group>
{
public GroupMap()
{
Table(TableNames.Group);
Id(x => x.Id).GeneratedBy.Native();
Map(x => x.Name).Not.Nullable();
...
References<Group>(x => x.Parent);
}
}
With this configuration, Fluent NHibernate creates these tables:
GroupEntry
bigint Id string Name ... bigint Group_id
Group
bigint Id string Name ... bigint Parent_id bigint GroupEntry_id
I don't know why it creates the column "GroupEntry_id" in the "Group" table. I am only mapping the other side of the relation. Is there an error in my configuration or is this a bug?
The fact that "GroupEntry_id" is created with a "not null" constraint gives me a lot of trouble, otherwise I would probably not care.
I'd really appreciate any help on this, it has been bugging me for a while and I cannot find any posts with a similar problem.
Edit: I do NOT want to create a bidirectional association!
If you want a many-to-one where a Group has many Group Entries I would expect your models to look something like this:
public class GroupEntry : IGroupEntry
{
public virtual long Id { get; set; }
public virtual string Name { get; set; }
...
public virtual IGroup Group { get; set; }
}
public class Group : IGroup
{
public virtual long Id { get; set; }
public virtual string Name { get; set; }
...
public virtual IList<GroupEntry> GroupEntries { get; set; }
public virtual IGroup Parent { get; set; }
}
Notice that the Group has a list of its GroupEntry objects. You said:
I don't know why it creates the column "GroupEntry_id" in the "Group" table. I am only mapping the other side of the relation.
You need to map both sides of the relationship, the many side and the one side. Your mappings should look something like:
public GroupEntryMap()
{
Table(TableNames.GroupEntry);
Id(x => x.Id).GeneratedBy.Native();
Map(x => x.Name).Not.Nullable();
...
References<Group>(x => x.Group); //A GroupEntry belongs to one Group
}
}
public class GroupMap : ClassMap<Group>
{
public GroupMap()
{
Table(TableNames.Group);
Id(x => x.Id).GeneratedBy.Native();
Map(x => x.Name).Not.Nullable();
...
References<Group>(x => x.Parent);
//A Group has-many GroupEntry objects
HasMany<GroupEntry>(x => x.GroupEntries);
}
}
Check out the fluent wiki for more examples.
The solution was that I accidentally assigned the same table name for two different entities... Shame on me :(
Thanks a lot for the input though!

Fluent NHibernate : How to map a 'Foreign Key' column in the mapping class

I'm starting to develop with Fluent NHiberate, and I was wondering how I create a defined 'Foreign Key' relationship in my Mapping class.
Here's my class. These classes are a one-to-one with associated tables.
public class Song
{
public virtual int SongID{ get; private set; } //Primary Key
public virtual int SongArtistID { get; set; } //Foreign Key mapping to 'Artist.ArtistID'
public virtual string Title { get; set; }
}
public class Artist
{
public virtual int ArtistID{ get; private set; } //Primary Key
public virtual int ArtistName{ get; set; }
}
public class SongMapping : ClassMap<Song>
{
SongMapping()
{
Id(c => c.SongID);//.GeneratedBy.HiLo("sermon"); is HiLo generator good?
Map(c => c.SermonArtistID).Not.Nullable(); //How is this mapped to 'Artist.ArtistID'??
Map(c => c.Title).Not.Nullable().Length(50);
}
}
In my mapping file, I want to create a defined foreign key relationship in my Song class SongArtistID column, which will define a foreign key to the ArtistID column in the Artist table/class.
Here you go:
public class Song
{
public virtual int Id { get; private set; }
public virtual Artist Artist { get; set; }
public virtual string Title { get; set; }
public class SongMap : ClassMap<Song>
{
SongMap()
{
Id(c => c.Id);
References(c => c.Artist); // Yes, that's all.
Map(c => c.Title).Not.Nullable().Length(50);
}
}
}
That being said, it's easier using the Automapper configuration.
I have things to work with identifiers via next (tested on my entities, here just renamed things and no run was done, please consider it as patter to try):
References<Artist>(x => x.SongArtistID ).Column("SongArtistID").ForeignKey("ArtistID");

Fluent NHibernate Many to one mapping

I am creating a NHibenate application with one to many relationship. Like City and State data.
City table
CREATE TABLE [dbo].[State](
[StateId] [varchar](2) NOT NULL primary key,
[StateName] [varchar](20) NULL)
CREATE TABLE [dbo].[City](
[Id] [int] primary key IDENTITY(1,1) NOT NULL ,
[State_id] [varchar](2) NULL refrences State(StateId),
[CityName] [varchar](50) NULL)
My mapping is follows
public CityMapping()
{
Id(x => x.Id);
Map(x => x.State_id);
Map(x => x.CityName);
HasMany(x => x.EmployeePreferedLocations)
.Inverse()
.Cascade.SaveUpdate();
References(x => x.State)
//.Cascade.All();
//.Class(typeof(State))
//.Not.Nullable()
.Cascade.None()
.Column("State_id");
}
public StateMapping()
{
Id(x => x.StateId)
.GeneratedBy.Assigned();
Map(x => x.StateName);
HasMany(x => x.Jobs)
.Inverse();
//.Cascade.SaveUpdate();
HasMany(x => x.EmployeePreferedLocations)
.Inverse();
HasMany(x => x.Cities)
// .Inverse()
.Cascade.SaveUpdate();
//.Not.LazyLoad()
}
Models are as follows:
[Serializable]
public partial class City
{
public virtual System.String CityName { get; set; }
public virtual System.Int32 Id { get; set; }
public virtual System.String State_id { get; set; }
public virtual IList<EmployeePreferedLocation> EmployeePreferedLocations { get; set; }
public virtual JobPortal.Data.Domain.Model.State State { get; set; }
public City(){}
}
public partial class State
{
public virtual System.String StateId { get; set; }
public virtual System.String StateName { get; set; }
public virtual IList<City> Cities { get; set; }
public virtual IList<EmployeePreferedLocation> EmployeePreferedLocations { get; set; }
public virtual IList<Job> Jobs { get; set; }
public State()
{
Cities = new List<City>();
EmployeePreferedLocations = new List<EmployeePreferedLocation>();
Jobs = new List<Job>();
}
//public virtual void AddCity(City city)
//{
// city.State = this;
// Cities.Add(city);
//}
}
My Unit Testing code is below.
City city = new City();
IRepository<State> rState = new Repository<State>();
Dictionary<string, string> critetia = new Dictionary<string, string>();
critetia.Add("StateId", "TX");
State frState = rState.GetByCriteria(critetia);
city.CityName = "Waco";
city.State = frState;
IRepository<City> rCity = new Repository<City>();
rCity.SaveOrUpdate(city);
City frCity = rCity.GetById(city.Id);
The problem is , I am not able to insert record. The error is below.
"Invalid index 2 for this SqlParameterCollection with Count=2."
But the error will not come if I comment State_id mapping field in the CityMapping file. I donot know what mistake is I did. If do not give the mapping Map(x => x.State_id); the value of this field is null, which is desired. Please help me how to solve this issue.
Few remarks:
Remove this State_id property from the City class and the mapping. You already have a State property so it makes no sense in your object model.
Those Jobs and EmployeePreferedLocations properties in the State class don't have any related columns/tables in your database (at least the one you've shown here) while you have mappings for them.

How to map this legacy table with NHibernate (Fluent)?

New to NHibernate. Having trouble wrapping my head around how to map this legacy table.
CREATE TABLE [dbo].[CmnAddress](
[addressId] [int] NOT NULL,
[objectType] [varchar](63) NULL,
[objectId] [int] NULL,
[addressType] [varchar](7) NULL,
[recordStatus] [char](1) NULL,
[fromDate] [int] NULL,
[toDate] [int] NULL,
[onStreet] [varchar](254) NULL,
[atStreet] [varchar](254) NULL,
[unit] [varchar](30) NULL,
[city] [varchar](254) NULL,
[state] [varchar](30) NULL,
[zipCode] [varchar](30) NULL,
)
There is also a "CmnPerson" table that I have mapped to a Person class. I need the Person class to contain a list of Addresses, where the objectType column contains "CmnPerson" and the objectId field matches my Person.Id ("CmnPerson.personId") field.
I am also later going to have to create a Contact class that also contains a list of Addresses where the objectType column contains "CmnContact".
I'm having a very tough time figuring out if I should be using the Any mapping or class-hierarchy-per-table with discrimination on subcolumns? Or if either of those will even meet my needs.
Can anyone show my how to map this Address class? Fluent config would be preferable.
ADDED INFO:
The following classes and mappings almost work, but the Addresses list return ALL rows from the CmnAddress table with a matching objectId, regardless of the objectType field's value. I think I could use an ApplyFilter on the HasMany mapping for Person.Addresses, but that doesn't seem like the "right" way.
More added info: I was able to resolve this last issue by chaining AlwaysSelectWithValue() on after the call to DiscriminateSubClassesOnColumn(...)
public class Person
{
public virtual int Id { get; private set; }
public virtual string LastName { get; set; }
public virtual string FirstName { get; set; }
public virtual string MiddleName { get; set; }
public virtual string Gender { get; set; }
public virtual IList<PassClient> PassClients { get; set; }
public virtual IList<PersonAddress> Addresses { get; set; }
}
public class PersonMap : ClassMap<Person>
{
public PersonMap() {
Table("CmnPerson");
Id(x => x.Id).Column("personId");
Map(x => x.LastName);
Map(x => x.FirstName);
Map(x => x.MiddleName);
Map(x => x.Gender);
HasMany(x => x.PassClients).KeyColumn("personId");
HasMany(x => x.Addresses).KeyColumn("objectId");
}
}
abstract public class Address
{
public virtual int Id { get; private set; }
public virtual string StreetNo { get; set; }
public virtual string OnStreet { get; set; }
public virtual string Unit { get; set; }
public virtual string City { get; set; }
public virtual string State { get; set; }
public virtual string ZipCode { get; set; }
}
public class PersonAddress : Address {
public virtual Person Person { get; set; }
}
public class AddressMap : ClassMap<Address>
{
public AddressMap() {
Table("CmnAddress");
Id(x => x.Id).Column("addressId");
Map(x => x.StreetNo);
Map(x => x.OnStreet);
Map(x => x.Unit);
Map(x => x.City);
Map(x => x.State);
Map(x => x.ZipCode);
DiscriminateSubClassesOnColumn("objectType").AlwaysSelectWithValue();
}
}
public class PersonAddressMap : SubclassMap<PersonAddress>
{
public PersonAddressMap() {
DiscriminatorValue("CmnPerson");
References(x => x.Person).Column("objectId");
}
}
You can not use the Any-mapping when it's a has many relation. It can be used, when an address can point to different kinds of objects - like a person, an order or other things not related.
To map the hierarachy you can do it like this:
public class CmnAddressMap : ClassMap<CmnAddress>
{
public CmnAddressMap()
{
Id(x => x.addressId);
Map(x => x...);
DiscriminateSubClassesOnColumn("objectType");
}
}
public class PersonAdressMap : SubclassMap<PersonAddress>
{
public PersonAdressMap()
{
DiscriminatorValue("objectType1");
}
}
public class ContactAdressMap : SubclassMap<ContactAddress>
{
public ContactAdressMap()
{
DiscriminatorValue("objectType2");
}
}
Have an abstract CmnAddress with all the fields (map all the fields in the CmnAdressMap for example) and two subclasses named PersonAddress and ContactAddress.
And the person should then have a collection like IList which should mapped with HasMany. And you should be done.
Sorry, am not familiar with fluent mappings, however, one way to do it would be:
Create an Address abstract class with properties corresponding to all the columns in your table except for objectType
Create a PersonAddress class which extends Address
Create a ContactAddress class which extends Address
Map all the columns of CmnAddress to properties of the Address class in the normal way, except for objectType which you declare as the discriminator column
Map PersonAddress as a subclass of Address with discriminator value "CmnPerson"
Map ContactAddress as a subclass of Address with a discriminator value of "CmnContact"
In code, your Person class would hold a list of PersonAddresses and your Contact class would hold a list of ContactAddresses
Address class
public class Address
{
public virtual int Id { get; set; }
public virtual Person Person { get; set; }
// etc.
}
Person class
public class Person
{
public Person()
{
Addresses = new List<Address>();
}
public virtual int Id { get; set; }
// etc.
public virtual IList<Address> Addresses { get; set; }
}
AddressMap
public class AddressMap : ClassMap<Address>
{
public AddressMap()
{
Table("CmnAddress");
Id(x => x.Id).Column("addressId");
// etc.
References(x => x.Person);
}
}
To separate the difference between Address => Person and Address => Contact, you'll want to read up on NHibernate's polymorphism and discriminate sub classes based on column.