Fluent NHibernate Many to one mapping - nhibernate

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.

Related

Nhibernate databinding foreign key to lookupedit

I would like to databind the foreign key property Product.CategoryId to a Devexpess Lookupedit in Windows Forms Application.
So
lookEditCategory.DataBindings
.Add(new Binding("EditValue", Product, "CategoryId ", true,
DataSourceUpdateMode.OnPropertyChanged));
lookEditCategory.Properties.Columns.Clear();
lookEditCategory.Properties.NullText = "";
lookEditCategory.Properties.DataSource = CatCol;
lookEditCategory.Properties.ValueMember = "CategoryId";
lookEditCategory.Properties.DisplayMember = "CategoryName";
var col = new LookUpColumnInfo("CategoryName") { Caption = "Type" };
lookEditCategory.Properties.Columns.Add(col);
The problem is that Nhibernate does not expose the foreign key Product.CategoryId. Instead my entity and mapping are like this
public partial class Product
{
public virtual int ProductId { get; set; }
[NotNull]
[Length(Max=40)]
public virtual string ProductName { get; set; }
public virtual bool Discontinued { get; set; }
public virtual System.Nullable<int> SupplierId { get; set; }
[Length(Max=20)]
public virtual string QuantityPerUnit { get; set; }
public virtual System.Nullable<decimal> UnitPrice { get; set; }
public virtual System.Nullable<short> UnitsInStock { get; set; }
public virtual System.Nullable<short> UnitsOnOrder { get; set; }
public virtual System.Nullable<short> ReorderLevel { get; set; }
private IList<OrderDetail> _orderDetails = new List<OrderDetail>();
public virtual IList<OrderDetail> OrderDetails
{
get { return _orderDetails; }
set { _orderDetails = value; }
}
public virtual Category Category { get; set; }
public class ProductMap : FluentNHibernate.Mapping.ClassMap<Product>
{
public ProductMap()
{
Table("`Products`");
Id(x => x.ProductId, "`ProductID`")
.GeneratedBy
.Identity();
Map(x => x.ProductName, "`ProductName`")
;
Map(x => x.Discontinued, "`Discontinued`")
;
Map(x => x.SupplierId, "`SupplierID`")
;
Map(x => x.QuantityPerUnit, "`QuantityPerUnit`")
;
Map(x => x.UnitPrice, "`UnitPrice`")
;
Map(x => x.UnitsInStock, "`UnitsInStock`")
;
Map(x => x.UnitsOnOrder, "`UnitsOnOrder`")
;
Map(x => x.ReorderLevel, "`ReorderLevel`")
;
HasMany(x => x.OrderDetails)
.KeyColumn("`ProductID`")
.AsBag()
.Inverse()
.Cascade.None()
;
References(x => x.Category)
.Column("`CategoryID`");
}
}
}
I cannot add the property CategoryID in my Product entity and mapping because then it will be mapped twice.
Is there any solution?
Yes. Do NOT use your domain entities in the UI.
Sometimes your UI doesn't need (and shouldn't be aware of) all the properties of your domain objects.
Other times, it needs DTOs that contain data from different domain sources (for example- a list of CourseNames for the Student screen), or, like in your case- it needs the data to be represented in a slightly different way.
So the best way would be to create your DTOs with all (and only) the properties needed by the UI.
See this SO question for further details.

fluent nhibernate hasmany relationship could not insert

I have the following tables:
LANDLORD = Id (Primary Key), FirstName, Surname, EmailAddress, Title;
PROPERTY = Id (Primary Key), Type, NumberOfBedrooms, Address1, Address2, City, County, PostCode, LandlordId (Foreign Key to Landlord entity);
My Domain classes are:
public class Landlord:BaseEntity
{
public virtual string Title { get; set; }
public virtual string Surname { get; set; }
public virtual string FirstName { get; set; }
public virtual string EmailAddress { get; set; }
public virtual IList<Property> Properties { get; set; }
public Landlord()
{
Properties = new List<Property>();
}
}
public class Property:BaseEntity
{
public virtual string Type { get; set; }
public virtual int NumberOfBedrooms { get; set;}
public virtual string Address1 { get; set; }
public virtual string Address2 { get; set; }
public virtual string City { get; set; }
public virtual string County { get; set; }
public virtual string PostCode { get; set; }
public virtual Landlord Landlord { get; set; }
}
My Fluent NHibernate maps are:
public sealed class LandlordMap:ClassMap<Landlord>
{
public LandlordMap()
{
Id(x => x.Id).GeneratedBy.Identity();
Map(x => x.Title);
Map(x => x.Surname);
Map(x => x.FirstName);
Map(x => x.EmailAddress);
HasMany(x => x.Properties)
.KeyColumns.Add("LandlordId")
.Inverse()
.Cascade.All();
Table("LANDLORD");
}
}
public sealed class PropertyMap:ClassMap<Property>
{
public PropertyMap()
{
Id(x => x.Id).GeneratedBy.Identity();
Map(x => x.Type);
Map(x => x.NumberOfBedrooms);
Map(x => x.Address1);
Map(x => x.Address2);
Map(x => x.City);
Map(x => x.County);
Map(x => x.PostCode);
References(x => x.Landlord, "LandlordId");
Table("PROPERTY");
}
}
To test that a Landlord is saved to the database, I have the following code:
public class Program
{
static void Main(string[] args)
{
ILandlordRepository rep = new LandlordRepository();
//Create property object
Property p1 = new Property
{
Address1 = "123 LA Road",
Address2 = "Bilston",
City = "Harlem",
County = "West Mids",
NumberOfBedrooms = 2,
PostCode = "wv134wd",
Type = "Bungalow"
};
//Create landlord and assign property
var landlord = new Landlord();
landlord.Title = "Dr";
landlord.FirstName = "Rohit";
landlord.Surname = "Kumar";
landlord.EmailAddress = "rkhkp#p.com";
landlord.Properties.Add(p1);
//Add to the database
rep.SaveOrUpdate(landlord);
Console.ReadKey();
}
}
When I call SaveOrUpdate I get this error:
could not insert: [Homes4U.Service.DomainClasses.Property][SQL: INSERT INTO PROPERTY (Type, NumberOfBedrooms, Address1, Address2, City, County, PostCode, LandlordId) VALUES (?, ?, ?, ?, ?, ?, ?, ?); select SCOPE_IDENTITY()]
Does anybody now why this is happening?
In your mappings, you've specified that the Property object is responsible for saving its reference to Landlord.
HasMany(x => x.Properties)
.KeyColumns.Add("LandlordId")
// Inverse means that the other side of the
// relationship is responsible for creating the reference
.Inverse()
.Cascade.All();
When you attempt to save the object, the Property object in the Properties collection has no reference to the landlord it belongs to. Under the hood, it'll attempt to insert a NULL into the LandlordId column.
This is why you are getting your error.
EDIT
To resolve, save the landlord first, without a reference to any property.
ILandlordRepository rep = new LandlordRepository();
IPropertyRepository pro = new PropertyRepository();
//Create landlord
var landlord = new Landlord();
landlord.Title = "Dr";
landlord.FirstName = "Rohit";
landlord.Surname = "Kumar";
landlord.EmailAddress = "rkhkp#p.com";
rep.SaveOrUpdate(landlord);
// Now add the landlord reference to the property and
// save
/Create property object
Property p1 = new Property
{
Address1 = "123 LA Road",
Address2 = "Bilston",
City = "Harlem",
County = "West Mids",
NumberOfBedrooms = 2,
PostCode = "wv134wd",
Type = "Bungalow",
Landlord = landlord
};
pro.SaveOrUpdate(p1);
You may need to reload the Landlord after saving it.
EDIT 2
See this question on Inverse.
Inverse Attribute in NHibernate

Nhibernate error 'Invalid column name' when column does exist

Hi I have an object called document and one called user
Document
public virtual string Name { get; set; }
public virtual string Description { get; set; }
public virtual User User { get; set; }
Documentmap
public DocumentMap()
{
Map(x => x.Name);
Map(x => x.Description);
References(x => x.User);
}
User
public virtual string UserId { get; set; }
public virtual string FirstName { get; set; }
public virtual string MiddleInitial { get; set; }
public virtual string LastName { get; set; }
private readonly IList<Document> _documents = new List<Document>();
public virtual IEnumerable<Document> Documents { get { return _documents; } }
public virtual void Remove(Document document)
{
_documents.Remove(document);
}
public virtual void Add(Document document)
{
if (!document.IsNew() && _documents.Contains(document)) return;
_documents.Add(document);
}
Map(x => x.UserId);
Map(x => x.FirstName);
Map(x => x.MiddleInitial);
Map(x => x.LastName);
HasMany(x => x.Documents).Access.CamelCaseField(Prefix.Underscore);
Pretty straighforward ( they inherit from base class with stuff like createddate modifieddate etc )
when I try to get all doc by userid I get this
Invalid column name 'UserId'.
the column most definitely is in the table. It also lists several of the base class items as not being there.
I take the sql and past it in query manager and I get intellisense saying they are invalid columns. I run it and it executes just fine. Further more there are plenty of other objects using these base classes with no problems.
I have tried various things like explicitly mapping the key name, the column name using inverse etc to no avail. Don't really know what to do.
Thanks,
Raif
//EDIT as per request sorry it's so verbose. the database is created by nhibernate create schema
Document
public class Document : Entity
{
public virtual string Name { get; set; }
public virtual string Description { get; set; }
public virtual DocumentCategory DocumentCategory { get; set; }
[ValueOf(typeof(DocumentFileType))]
public virtual string FileType { get; set; }
public virtual string FileUrl { get; set; }
public virtual int? Pages { get; set; }
public virtual decimal? Size { get; set; }
public virtual User User { get; set; }
}
public class DocumentMap : EntityMap<Document>
{
public DocumentMap()
{
Map(x => x.Name);
Map(x => x.Description);
Map(x => x.FileUrl);
Map(x => x.Pages);
Map(x => x.Size);
Map(x => x.FileType);
References(x => x.DocumentCategory);
References(x => x.User);
}
}
Entity
public class Entity : IGridEnabledClass, IEquatable<Entity>
{
public virtual int EntityId { get; set; }
public virtual DateTime? CreateDate { get; set; }
public virtual DateTime? ChangeDate { get; set; }
public virtual int ChangedBy { get; set; }
public virtual bool Archived { get; set; }
public virtual bool IsNew()
{
return EntityId == 0;
}
User
public class User : DomainEntity, IUser
{
public virtual string UserId { get; set; }
[ValidateNonEmpty]
public virtual string FirstName { get; set; }
public virtual string MiddleInitial { get; set; }
[ValidateNonEmpty]
public virtual string LastName { get; set; }
public virtual string Title { get; set; }
public virtual DateTime? BirthDate { get; set; }
public virtual string StartPage { get; set; }
public virtual UserLoginInfo UserLoginInfo { get; set; }
public virtual UserStatus UserStatus { get; set; }
public virtual Photo HeadShot { get; set; }
private readonly IList<Document> _documents = new List<Document>();
public virtual IEnumerable<Document> Documents { get { return _documents; } }
public virtual void Remove(Document document)
{
_documents.Remove(document);
}
public virtual void Add(Document document)
{
if (!document.IsNew() && _documents.Contains(document)) return;
_documents.Add(document);
}
several more collections
public class UserMap : DomainEntityMap<User>
{
public UserMap()
{
Map(x => x.UserId);
Map(x => x.FirstName);
Map(x => x.MiddleInitial);
Map(x => x.LastName);
Map(x => x.BirthDate);
Map(x => x.StartPage);
References(x => x.UserStatus);
References(x => x.UserLoginInfo);
References(x => x.HeadShot);
HasMany(x => x.Documents).Access.CamelCaseField(Prefix.Underscore);
database tables create from script select to menu item on management studio
SELECT [EntityId]
,[CreateDate]
,[ChangeDate]
,[ChangedBy]
,[Archived]
,[Name]
,[Description]
,[FileUrl]
,[Pages]
,[Size]
,[FileType]
,[DocumentCategoryId]
,[UserId]
FROM [DecisionCriticalSuite].[dbo].[Document]
GO
SELECT [EntityId]
,[CreateDate]
,[ChangeDate]
,[ChangedBy]
,[Archived]
,[TenantId]
,[OrgId]
,[UserId]
,[FirstName]
,[MiddleInitial]
,[LastName]
,[BirthDate]
,[StartPage]
,[UserStatusId]
,[UserLoginInfoId]
,[HeadShotId]
,[OrganizationId]
FROM [DecisionCriticalSuite].[dbo].[User]
GO
error from nhprof
ERROR:
Invalid column name 'UserId'.
Invalid column name 'UserId'.
Invalid column name 'EntityId'.
Invalid column name 'EntityId'.
Invalid column name 'CreateDate'.
Invalid column name 'ChangeDate'.
Invalid column name 'ChangedBy'.
Invalid column name 'Archived'.
Invalid column name 'FileType'.
Invalid column name 'UserId'.Could not execute query: SELECT documents0_.UserId as UserId1_, documents0_.EntityId as EntityId1_, documents0_.EntityId as EntityId49_0_, documents0_.CreateDate as CreateDate49_0_, documents0_.ChangeDate as ChangeDate49_0_, documents0_.ChangedBy as ChangedBy49_0_, documents0_.Archived as Archived49_0_, documents0_.Name as Name49_0_, documents0_.Description as Descript7_49_0_, documents0_.FileUrl as FileUrl49_0_, documents0_.Pages as Pages49_0_, documents0_.Size as Size49_0_, documents0_.FileType as FileType49_0_, documents0_.DocumentCategoryId as Documen12_49_0_, documents0_.UserId as UserId49_0_ FROM [Document] documents0_ WHERE documents0_.UserId=#p0
Make sure nhibernate is querying against the same database as what you are querying against in sql management studio.
I just had the same issue because I had mapped Entity1.Entity2 as Entity3.
So when joining, it would attempt to use a property from Entity3 as if it existed on Entity2.

FluentNhibernate HasManytoMany Relation - It doesnt add into the link table

Using fluentnhibernate i am having a problem with the link table insertion.
Here is my entities
public partial class Item
{
public virtual int Id
{
get;
set;
}
public virtual string Description
{
get;
set;
}
public virtual IList<Category> Categories
{
get;
set;
}
}
public partial class Category
{
public virtual int Id
{
get;
set;
}
public virtual string Name
{
get;
set;
}
public virtual string Description
{
get;
set;
}
public virtual IList<Item> Items
{
get;
set;
}
}
Here is my mappings.
public class ItemMapping : ClassMap<Item>
{
public ItemMapping()
{
Table("Item");
Schema("dbo");
Id(x => x.Id);
Map(x => x.Description);
HasManyToMany(x => x.Categories)
.ChildKeyColumn("Item_id")
.ParentKeyColumn("Category_id")
.Table("CategoriesToItems")
.AsSet();
}
}
public class CategoryMapping : ClassMap<Category>
{
public CategoryMapping()
{
Table("Category");
Schema("dbo");
Id(x => x.Id);
Map(x => x.Description);
Map(x => x.Name);
HasManyToMany(x => x.Items)
.ChildKeyColumn("Category_id")
.ParentKeyColumn("Item_id")
.Table("CategoriesToItems")
.AsSet();
}
}
Here is how i add it to collection in my mvc page
var category = CategoryTask.Query(x => x.Id == post.Category).FirstOrDefault();
var item = new Item
{
Categories = new List<Category> { category },
Tags = tags
};
ItemTasks.Save(item);
My question is why it doesnt add the relations in my link table "CategoriesToItems". The table is already in the database with Category_Id (FK, int, not null) and Item_Id (FK, int, not null).
Where is the problem? why it doesnt add it to relation table?
It's hard to say what's really wrong when we can't see what your ItemTasks.Save does under the covers. Are you wrapping your save in a transaction? If not, you should be.
You should call Session.Flush() just before the transaction.Commit() as well.
I am not certain if the problem has been solved, but it looks similar to my problem (fluentnhibernate hasmanytomany same identifier exception).
Also, it looks like your parent and child key columns are backward.

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.