Fluent Nhibernate Nunit Test Error - nhibernate

I am trying to learn Nhibernate using fluent nhibernate mappings and i have created a small test app. Below is the code:
UserClass:
public class User
{
public string UserName { get; set; }
public string Password { get; set; }
public string Role { get; set; }
public string Email { get; set; }
public DateTime JoinDate { get; set; }
}
User Map Class:
public class UserMapping: ClassMap<User>
{
public UserMapping()
{
WithTable("UserT");
Not.LazyLoad();
Id(u => u.UserName);
Map(u => u.Password);
Map(u => u.Role);
Map(u => u.Email);
Map(u => u.JoinDate);
}
}
DAL User Class:
public class DALUser
{
public User GetUserByUserName(string userName)
{
ISessionFactory sessionFactory = Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2005.ConnectionString(c => c.Server("ServerName").Database("DBName").TrustedConnection()))
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<UserMapping>()).BuildSessionFactory();
ISession session = sessionFactory.OpenSession();
return session.Get<User>(userName);
}
}
Nunit Test Class:
[TestFixture]
public class UserTest
{
[Test]
public void CanGetUserByUserName()
{
DALUser user1 = new DALUser();
Assert.AreEqual("testUser", user1.GetUserByUserName("testUser").UserName);
}
}
When i try to run the test class i get the following error :Object reference not set to an instance of an object.
I have placed a breakpoint in the GetUserByUserName method and noticed that its returning a null user. But i am not able to figure out why this is happening. Can anyone help me?

Take a look is your database configuration correct?
Are you sure that you database server is "ServerName"
and you have existing Database "DBName"

Related

Doesn't update many to many attribute using NHibernate

Suppose I have only two classes: Group and User. User has groups and Group has members (instance of users)
public class User {
public virtual int id { set; get; }
public virtual string username { set; get; }
public virtual IList<Group> groups { set; get; }
public User()
{
groups = new List<Group>();
}
public virtual void joinGroup(Group group)
{
if (this.groups.Contains(group))
throw new AlreadyJoinedException();
group.members.Add(this);
this.groups.Add(group);
}
public class Group
{
public virtual int id { set; get; }
public virtual string name { set; get; }
public virtual User administrator { set; get; }
public virtual IList<User> members { set; get; }
public Group()
{
members = new List<User>();
}
As you can see the domain it's quite simple. I've already mapped both classes correctly using Fluent NHibernate,
public class UserMapping : ClassMap<User>
{
public UserMapping()
{
this.Id(user => user.id).GeneratedBy.Identity();
this.Map(user => user.username).Not.Nullable().Length(50).Not.LazyLoad();
this.HasManyToMany(user => user.groups).Table("MemberPerGroup").ParentKeyColumn("id_user").ChildKeyColumn("id_group").Not.LazyLoad();
}
}
public class GroupMapping : ClassMap<Group>
{
public GroupMapping()
{
this.Id(group => group.id).GeneratedBy.Identity();
this.Map(group => group.name).Not.Nullable().Length(50).Not.LazyLoad();
this.References(group => group.administrator).Not.Nullable().Not.LazyLoad();
this.HasManyToMany(group => group.members).Table("MemberPerGroup").ParentKeyColumn("id_group").ChildKeyColumn("id_user").Not.LazyLoad();
}
}
I'm progamming a web application using ASP MVC 4. My problem shows up when a user tries to join group. It doesn't break but it neither works fine (doesn't insert into the table the new row in MemberPerGroup). I'm doing something like it:
public void JoinGroup(User user,Group group){
this.userRepository.GetSessionFactory().TransactionalInterceptor(() =>
{
user.joinGroup(group);
});
}
Thanks in advance.
Ivan.
It seems your mapping has no cascading set?
this.HasManyToMany(group => group.members)
.Table("MemberPerGroup")
.ParentKeyColumn("id_group")
.ChildKeyColumn("id_user")
.Not.LazyLoad()
.Cascade.SaveUpdate();
I'm curious - why do you use GetSessionFactory()? our repositories take an ISession object in the constructor, (injected by autofac, but that's irrelevant) from which we start our queries:
// even better to use a transaction, but this is just a sample
_session.SaveOrUpdate(user);
_session.Flush();

NHibernate bi-directional association

I am trying to model a parent/child association where a Parent class (Person) owns many instances of a child class (OwnedThing) - I want the OwnedThing instances to be saved automatically when the Person class is saved, and I want the association to be bi-directional.
public class Person
{
public class MAP_Person : ClassMap<Person>
{
public MAP_Person()
{
this.Table("People");
this.Id(x => x.ID).GeneratedBy.GuidComb().Access.BackingField();
this.Map(x => x.FirstName);
this.HasMany(x => x.OwnedThings).Cascade.AllDeleteOrphan().KeyColumn("OwnerID").Inverse();
}
}
public virtual Guid ID { get; private set; }
public virtual string FirstName { get; set; }
public virtual IList<OwnedThing> OwnedThings { get; set; }
public Person()
{
OwnedThings = new List<OwnedThing>();
}
}
public class OwnedThing
{
public class MAP_OwnedThing : ClassMap<OwnedThing>
{
public MAP_OwnedThing()
{
this.Table("OwnedThings");
this.Id(x => x.ID).GeneratedBy.GuidComb().Access.BackingField();
this.Map(x => x.Name);
this.References(x => x.Owner).Column("OwnerID").Access.BackingField();
}
}
public virtual Guid ID { get; private set; }
public virtual Person Owner { get; private set; }
public virtual string Name { get; set; }
}
If I set Person.OwnedThings to Inverse then the OwnedThing instances are not saved when I save the Person. If I do not add Inverse then the save is successful but person.OwnedThings[0].Owner is always null after I retrieve it from the DB.
UPDATE
When saving the data NHibernate will set the single association end in the database because it is set via the many-end of the association, so when I retrieve the OwnedThing from the DB it does have the link back to the Person set. My null reference was from Envers which doesn't seem to do the same thing.
Am I understanding you correctly that your problem only occur on "history" entities read by nhibernate envers?
If so, it might be caused by this bug
https://nhibernate.jira.com/browse/NHE-64
The workaround for now is to use Merge instead of (SaveOr)Update.
OwnedThings[0].Owner is most likely null because you are not setting it when you do the add. When using bidirectional relationships you have to do something like the below:
Person person = new Person();
OwnedThing pwnedThing = new OwnedThing();
pwnedThing.Owner = person;
person.OwnedThings.Add(pwnedThing);
If you do not explicity set the pwnedThing.Owner and you query that same object in the same ISession that you created it on it will be null. Typically I have add or remove methods that do this "extra" work for me. Take the below example:
public class Order : Entity
{
private IList<OrderLine> orderLines;
public virtual IEnumerable<OrderLine> OrderLines { get { return orderLines.Select(x => x); } }
public virtual void AddLine(OrderLine orderLine)
{
orderLine.Order = this;
this.orderLines.Add(orderLine);
}
public virtual void RemoveLine(OrderLine orderLine)
{
this.orderLines.Remove(orderLine);
}
}
public class OrderMap : ClassMap<Order>
{
public OrderMap()
{
DynamicUpdate();
Table("ORDER_HEADER");
Id(x => x.Id, "ORDER_ID");
HasMany(x => x.OrderLines)
.Access.CamelCaseField()
.KeyColumn("ORDER_ID")
.Inverse()
.Cascade.AllDeleteOrphan();
}
}

Fluent NHibernate? Am I doing this correctly?

I am new to using Fluent NHibernate and NHibernate for the first time. I've used a custom written mapper since about 2000 that was written in house. Made a switch to LinqToSQL about 2 years ago, and about 6 months ago to Entities.
I'd like to see what Fluent/NHibernate have to offer. However, I can't seem to get it to run correctly. The following is a copy of my classes, their references, the ClassMaps. Can someone tell me if this simple implementation is correct?
This is my mappings and object classes:
using System;
using FluentNHibernate.Mapping;
namespace MyData.Data.Mappings
{
public class Login
{
public virtual int LoginId { get; private set; }
public virtual string Username { get; set; }
public virtual User User { get; set; }
}
public class LoginClassMap : ClassMap<Login>
{
public LoginClassMap()
{
Table("Logins");
Id(d => d.LoginId).GeneratedBy.Guid();
Map(d => d.Username).Not.Nullable().Length(50);
HasOne(d => d.User).ForeignKey("UserId").Cascade.All();
}
}
public class User
{
public virtual Guid UserId{ get; private set; }
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
public virtual Login Login { get; set; }
}
public class UserClassMap : ClassMap<User>
{
public UserClassMap()
{
Table("Users");
Id(d => d.UserId).GeneratedBy.Guid();
Map(d => d.FirstName).Not.Nullable().Length(100);
Map(d => d.LastName).Not.Nullable().Length(100);
References(r => r.Login, "UserId").Not.Nullable();
}
}
}
This is my Repository:
using System;
using System.Linq;
using NHibernate;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate.Linq;
using MyData.Data.Mappings;
namespace MyData.Data.Repository
{
public class LoginRepository
{
private readonly ISessionFactory _sessionFactory;
ISession _session;
public LoginRepository()
{
_sessionFactory = this.CreateSessionFactory();
_session = _sessionFactory.OpenSession();
}
private ISessionFactory CreateSessionFactory()
{
string connString = "MyDataConnectionString";
FluentConfiguration config = Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2005.ConnectionString(
x => x.FromConnectionStringWithKey(connString)))
.ExposeConfiguration(
c => c.SetProperty("current_session_context_class", "webContext"))
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<Login>());
return config.BuildSessionFactory();
}
public IQueryable<Login> GetAllLogins()
{
return _session.Linq<Login>();
}
}
}
Whenever it gets to config.BuildSessionFactory() it throws the following error:
An invalid or incomplete configuration was used while creating a SessionFactory.
The inner Exception is:
Exception has been thrown by the target of an invocation.
Is this the correct way to approach this? Any ideas or tweaks would be greatly appreciated!
Sean, you cannot use GeneratedBy.Guid() on LoginId because it's an int. Try to use another generator or change the type of LoginId.
I suspect you cannot use "private set" on UserId because it's the Id.
Also, HasOne(d => d.User).ForeignKey("UserId") means that if you expose your database model from your mappings, the name of the FK constraint will be "UserId". It seems to me that your intention was to specify the name column that holds the PK on table "Users".
These links have more infos:
http://wiki.fluentnhibernate.org/Fluent_mapping
http://jagregory.com/writings/i-think-you-mean-a-many-to-one-sir/
one-to-one fluent nhibernate?
It seems you forgot to specify proxy factory. It can be done like this:
OracleDataClientConfiguration persistenceConfigurer = OracleDataClientConfiguration
.Oracle10
.ConnectionString(connectionStringBuilder => connectionStringBuilder.FromAppSetting("Main.ConnectionString"))
.ProxyFactoryFactory<ProxyFactoryFactory>()
.CurrentSessionContext<ThreadStaticSessionContext>()
.AdoNetBatchSize(25)
.DoNot.ShowSql();
FluentConfiguration cfg = Fluently.Configure()
.Database(persistenceConfigurer)
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<UserMap>());
return cfg.BuildConfiguration();

Problem with Fluent nhibernate

i have written a code like this
public class person
{
public person()
{
public virtual int Id { get; set; }
public virtual string Code { get; set; }
}
}
public class Child : Person
{
public person()
{
public virtual string Name{ get; set; }
public virtual string Lastname{ get; set; }
}
}
public class Book
{
public virtual int Id { get; set; }
public virtual string Name {get;set;}
}
and my Mapper classes is like these
public class PersonMapping : ClassMap<Person>
{
public PersonMapping()
{
Table("tblPersons");
Id(x => x.Id).GeneratedBy.Native();
Map(p => p.Code);
JoinedSubClass<Child>("Id", MapChild);
}
public static void MapChild(JoinedSubClassPart<Child> child)
{
child.Table("tblChilds");
child.Map(p => p.Name);
child.Map(p => p.Lastname);
child.HasMany(x => x.Relatives);
}
}
public class RelativeMapping : ClassMap<Relative>
{
public RelativeMapping()
{
Table("tblRelatives");
Id(x => x.Id);
Map(p => p.Name);
References(x => x.Child).Column("ChildId");
}
}
this is Configuration
Assembly assm = Assembly.Load("BLL");
return Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2008
.ConnectionString(c => c
.FromAppSetting("ConnStr"))
.Cache(c => c
.UseQueryCache()
.ProviderClass<HashtableCacheProvider>())
.ShowSql())
.Mappings(m => m.FluentMappings.AddFromAssembly(assm))
.BuildSessionFactory();
and this is the code of delete
public void Delete<T>(T obj)
{
ISessionFactory fact = FluentConfiguration.CreateSessionFactory();
ISession session = fact.OpenSession();
session.Delete(obj);
session.Flush();
}
my problem : when i wanna delete a Child it messages
" ILLEGAL ATTEMPT TO ASSOCIATE WITH TWO OPEN SESSION "
please help me
The error tells you the problem, and it is not with your entities or your mapping.
You have two or more open sessions and you're attempting to associate some entity with more than one of them.
update
In response to the updated code, I see that you have a method that accepts an entity as a parameter, creates a new session factory, creates a new session, and then tries to delete the entity.
There are some problems here:
You should only create the session factory once. Ever. This is an expensive operation.
You are passing the entity to the Delete() method. Where is this entity coming from? You've clearly already loaded it elsewhere in your application, using a different ISession. This is the crux of the problem. Unless you Evict() the entity from the first ISession (not recommended), trying to manipulate it with a different ISession will throw.
You're calling Flush() which should almost never be used.
You're using an implicit transaction.
You should really be deleting the entity with the same ISession with which it was loaded, and you should be performing work within a transaction, like this:
using(var transaction = session.BeginTransaction())
{
session.Delete(obj);
transaction.Commit();
}

NHibernate Auditing - PostInsert Not Working

My application has the following entities:
public class User
{
public virtual int UserID { get; set; }
public virtual string UserName { get; set; }
public virtual IList<UserLog> Log { get; private set; }
public User()
{
Log = new List<UserLog>();
}
}
public class UserLog
{
public virtual int UserLogID { get; set; }
public virtual User User { get; set; }
public virtual string UserName { get; set; }
public virtual DateTime DateCreated { get; set; }
}
With the following fluent mappings:
public class UserMap : ClassMap<User>
{
public UserMap()
{
Table("Users");
Id(x => x.UserID);
Map(x => x.UserName);
HasMany(x => x.Log)
.KeyColumn("UserID")
.OrderBy("DateCreated")
.Inverse()
.Cascade.All();
}
}
public class UserLogMap : ClassMap<UserLog>
{
public UserLogMap()
{
Table("UsersLog");
Id(x => x.UserLogID);
References(x => x.User, "UserID");
Map(x => x.UserName);
Map(x => x.DateCreated);
}
}
The UsersLog table simply logs any changes which are made to the User. I'm trying to hook this up automatically using the NHibernate event listeners. I have setup my configuration which successfully calls the following 2 methods:
public void OnPostInsert(PostInsertEvent #event)
{
if (#event.Entity is User)
InsertLog(#event.Entity);
}
public void OnPostUpdate(PostUpdateEvent #event)
{
if (#event.Entity is User)
InsertLog(#event.Entity);
}
Edit (here is the InsertLog method):
private void InsertLog(object entity)
{
var context = ServiceLocator.Current.GetInstance<IDataContext>();
var user = (User)entity;
context.Repository<UserLog>().Insert(new UserLog
{
User = user,
UserName = user.UserName,
DateCreated = DateTime.UtcNow
}); // Insert calls ISession.SaveOrUpdate(entity)
}
When i update a record a log is successfully inserted but when i insert a record i get an error telling me the UserID cannot be null in the UsersLog table. I've played around with a few different variations but nothing seems to work.
I'd really appreciate it if someone could show me how this can be done. Thanks
Solution posted in question comments. I simply had to use:
#event.Session.GetSession(NHibernate.EntityMode.Poco).Save(...);
to save the user instead of accessing the repository.