I'm trying to get Fluent and NHibernate configured properly with ASP.NET MVC. As far as I know it's configured properly but when I access the page that uses this setup I am not receiving any data results.
The model I'm using is called Brand and the database table is Brands.
Here is a snippet from my BrandController:
public ActionResult Index()
{
IRepository<Brand> repo = new BrandRepository();
var brands = repo.GetAll().ToList<Brand>();
return View(brands);
}
Here is a snippet from my BrandRepository:
ICollection<Brand> IRepository<Brand>.GetAll()
{
using (ISession session = NHibernateHelper.OpenSession())
{
var brands = session
.CreateCriteria(typeof(Brand))
.List<Brand>();
return brands;
}
}
Here is my NHibernateHelper:
public class NHibernateHelper
{
private static ISessionFactory _sessionFactory;
private static ISessionFactory SessionFactory
{
get
{
if (_sessionFactory == null)
{
_sessionFactory = Fluently.Configure()
.Database(
MsSqlConfiguration.MsSql2008
.ConnectionString(c => c
.FromConnectionStringWithKey("ShoesFullAccess")
)
)
.BuildSessionFactory();
}
return _sessionFactory;
}
}
public static ISession OpenSession()
{
return SessionFactory.OpenSession();
}
}
Here is my Brand model:
public class Brand
{
public int Id { get; private set; }
public virtual string Name { get; set; }
public virtual IList<Style> Styles { get; private set; }
public Brand()
{
Styles = new List<Style>();
}
public virtual void AddStyle(Style style)
{
Styles.Add(style);
}
}
And finally, here is my BrandMap:
public class BrandMap : ClassMap<Brand>
{
public BrandMap()
{
Id(x => x.Id);
Map(x => x.Name);
HasMany(x => x.Styles)
.Inverse()
.Cascade.All();
}
}
If anyone could point me in the right direction for how I can narrow down the problem I would very grateful!
You are not adding the mappings to the configuration.
Add this before .BuildSessionFactory():
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<BrandMap>())
I needed to make a few modifications to my code. The first and main one was adding the mappings to the configuration as Diego pointed out.
You are not adding the mappings to the configuration.
Add this before .BuildSessionFactory():
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<BrandMap>())
The next thing I had to fix was my Brand model. I needed to make the Id field virtual.
And finally, I needed to change my BrandMap just a little bit -- I had to specify exactly which table it was pointing to by adding this code Table("Brands");
Related
Suppose I have the following model
public class Customer
{
public virtual Guid Id { get; set; }
public virtual string Name { get; set; }
}
public class ActivityLog
{
public virtual Guid Id { get; set; }
public virtual Guid CustomerId { get; set; }
public virtual Customer Customer { get; set; }
public virtual DateTime ActivityDate { get; set; }
}
I would like to be able to remove customer and all corresponding ActivityLog items, by calling
session.Delete(customer);
What I don't want to is to have a property
List<ActivityLog> Logs in my Customer class. Is it possible to achieve in Nhibernate? I have tried EF, and it works there, but in HN getting reference constraint exception.
My mappings:
public class CustomerMap : ClassMapping<Customer>
{
public CustomerMap()
{
Id(x => x.Id, map => map.Generator(Generators.GuidComb));
Property(x => x.Name);
}
}
public class ActivityLogMap : ClassMapping<ActivityLog>
{
public ActivityLogMap()
{
Id(x => x.Id, map => map.Generator(Generators.GuidComb));
Property(x => x.ActivityDate);
ManyToOne(x => x.Customer, mapping =>
{
mapping.Class(typeof(Customer));
mapping.Column("CustomerId");
});
}
}
Maybe possible to have some extension hook and inspect mapping and do it manually for Nhibernate?
Edit: Here how it works with EF
public class CustomerEFMap : EntityTypeConfiguration<Customer>
{
public CustomerEFMap()
{
ToTable("Customer");
HasKey(x => x.Id);
Property(x => x.Name);
}
}
public class ActivityLogEFMap : EntityTypeConfiguration<ActivityLog>
{
public ActivityLogEFMap()
{
ToTable("ActivityLog");
HasKey(x => x.Id);
HasRequired(x => x.Customer).WithMany().HasForeignKey(x => x.CustomerId);
}
}
using (var context = new ObjectContext())
{
var customer = context.Set<Customer>().Find(id);
context.Set<Customer>().Remove(customer);
context.SaveChanges();
}
Having Customer and corresponding ActivityLog in DB, removes both
I would like to be able to remove customer and all corresponding
ActivityLog items, by calling
session.Delete(customer);
What I don't want to is to have a property List Logs in
my Customer class. Is it possible to achieve in Nhibernate?
NO. Impossible, not intended, not supported. NHibernate is ORM tool and will/can care about relations. Without relations, no care (no cascading)
But, we can always hide that List Property by making it protected
public class Customer
{
public virtual Guid Id { get; set; }
public virtual string Name { get; set; }
// HIDDEN in fact from consumers, managed by NHibernate
protected virtual IList<ActivitLog> { get; set; }
}
and the mapping with cascade in place - will do what is required.
As Radim Köhler states, I don't think there's any simple way to map the behaviour of a cascade without actually having the relationship. But as your reason for this is a plugin-based architecture, making use of a partial class might be what you need.
You can include the collection of ActivityLogs as a protected collection as part of a partial class in the plugin DLL. If your mapping then maps the collection, deleting the Customer will delete the ActivityLogs.
The following example should work - note that I'm using FluentNhibernate for the mapping.
This solution does rely on you be able to mark the Customer class as partial.
using FluentAssertions;
using FluentNHibernate;
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using FluentNHibernate.Mapping;
using NHibernate.Linq;
using NHibernate.Tool.hbm2ddl;
using NUnit.Framework;
using System;
using System.Collections.Generic;
namespace MapTest
{
public partial class Customer
{
public virtual Guid Id { get; set; }
public virtual string Name { get; set; }
}
public class ActivityLog
{
public virtual Guid Id { get; set; }
public virtual Customer Customer { get; set; }
public virtual DateTime ActivityDate { get; set; }
}
public class CustomerMap : ClassMap<Customer>
{
public CustomerMap()
{
Id(x => x.Id).GeneratedBy.Guid();
Map(x => x.Name);
HasMany<ActivityLog>(Reveal.Member<Customer>("ActivityLogs")).Cascade.All();
}
}
public class ActivityLogMap : ClassMap<ActivityLog>
{
public ActivityLogMap()
{
Id(x => x.Id).GeneratedBy.Guid();
Map(x => x.ActivityDate);
References(x => x.Customer);
}
}
// Part of your plugin DLL
public partial class Customer
{
protected virtual IList<ActivityLog> ActivityLogs { get; set; }
}
[TestFixture]
public class PartialClassCascade
{
[Test]
public void RunOnceToSetupDb()
{
Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2012.ConnectionString(#"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=MapTest;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"))
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<CustomerMap>())
.ExposeConfiguration(cfg => new SchemaUpdate(cfg).Execute(false, true))
.BuildSessionFactory();
}
[Test]
public void DeletingCustomerWithActivityLogs()
{
var sessionFactory = Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2012.ConnectionString(#"Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=MapTest;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"))
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<CustomerMap>())
.BuildSessionFactory();
using (var session = sessionFactory.OpenSession())
using (var tx = session.BeginTransaction())
{
session.CreateQuery("delete ActivityLog a").ExecuteUpdate();
session.CreateQuery("delete Customer c").ExecuteUpdate();
tx.Commit();
}
var homerId = default(Guid);
using (var session = sessionFactory.OpenSession())
using (var tx = session.BeginTransaction())
{
var homer = new Customer
{
Name = "Homer Simpson"
};
var monty = new Customer
{
Name = "Monty Burns"
};
session.Save(homer);
session.Save(monty);
homerId = homer.Id;
var activityLog1 = new ActivityLog
{
Customer = homer,
ActivityDate = DateTime.Now,
};
var activityLog2 = new ActivityLog
{
Customer = monty,
ActivityDate = DateTime.Now.AddDays(1),
};
session.Save(activityLog1);
session.Save(activityLog2);
tx.Commit();
}
using (var session = sessionFactory.OpenSession())
using (var tx = session.BeginTransaction())
{
var customer = session.Get<Customer>(homerId);
session.Delete(customer);
tx.Commit();
}
using (var session = sessionFactory.OpenSession())
using (var tx = session.BeginTransaction())
{
var customers = session.Query<Customer>();
var activityLogs = session.Query<ActivityLog>();
customers.Should().HaveCount(1);
activityLogs.Should().HaveCount(1);
}
}
}
}
I have created one console application by watching videos from http://www.d80.co.uk/post/2011/10/06/NHibernate-Video-Tutorial.aspx website. when i tried to executing the code its giving me following error:
An invalid or incomplete configuration was used while creating a SessionFactory. Check PotentialReasons collection, and InnerException for more detail.
but when i have downloaded the code and executed, its working fine. i have checked both the code and are same. so not under stand what i am doing wrong. i am posting my code here please help me to get out of this situation.
NhibernateHelper.cs
using FluentNHibernate.Cfg;
using FluentNHibernate.Cfg.Db;
using NHibernate;
using NHibernate.Tool.hbm2ddl;
using System;
namespace FluentNHibernate
{
class NhibernateHelper
{
private static ISessionFactory _sessionFactory;
private static ISessionFactory sessionFactory
{
get
{
if (_sessionFactory == null)
{
initialisationFactory();
}
return _sessionFactory;
}
}
private static void initialisationFactory()
{
try
{
_sessionFactory = Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2005.ConnectionString(#"Server=10.10.10.7;Database=TestDatabase;uid=sa;pwd=9ijnhy6;Trusted_Connection=false;").ShowSql())
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<Car>())
.ExposeConfiguration(cfg => new SchemaExport(cfg).Create(true, true))
.BuildSessionFactory();
}
catch (Exception e)
{
throw;
}
}
public static ISession OpenSession()
{
return sessionFactory.OpenSession();
}
}
}
Program.cs
using System;
using FluentNHibernate.Mapping;
namespace FluentNHibernate
{
internal class Program
{
public static void Main(string[] args)
{
using (var session = NhibernateHelper.OpenSession())
{
using (var transaction = session.BeginTransaction())
{
var fordMake = new Make
{
Name = "Ford"
};
var fiestaModel = new Model
{
Name = "Fiesta",
Make = fordMake
};
var car = new Car
{
Make = fordMake,
Model = fiestaModel,
Title = "Dans Car"
};
session.Save(car);
transaction.Commit();
Console.WriteLine("Created Car " + car.Title);
}
}
Console.ReadLine();
}
}
public class MakeMap : ClassMap<Make>
{
public MakeMap()
{
Id(x => x.Id);
Map(x => x.Name);
}
}
public class ModelMap : ClassMap<Model>
{
public ModelMap()
{
Id(x => x.Id);
Map(x => x.Name);
References(x => x.Make).Cascade.All();
}
}
public class CarMap : ClassMap<Car>
{
public CarMap()
{
Id(x => x.Id).GeneratedBy.HiLo("Car");
Map(x => x.Title);
References(x => x.Make).Cascade.All();
References(x => x.Model).Cascade.All();
}
}
public class Make
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
}
public class Model
{
public virtual int Id { get; set; }
public virtual string Name { get; set; }
public virtual Make Make { get; set; }
}
public class Car
{
public virtual int Id { get; set; }
public virtual string Title { get; set; }
public virtual Make Make { get; set; }
public virtual Model Model { get; set; }
}
}
Your NHibernateHelper.cs is considerably different than mine.
Try changing
_sessionFactory = Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2005.ConnectionString(#"Server=10.10.10.7;Database=TestDatabase;uid=sa;pwd=9ijnhy6;Trusted_Connection=false;").ShowSql())
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<Car>())
.ExposeConfiguration(cfg => new SchemaExport(cfg).Create(true, true))
.BuildSessionFactory();
To:
_sessionFactory = Fluently.Configure()
.Database(MsSqlConfiguration.MsSql2005.ConnectionString(c => c.FromConnectionStringWithKey("ConnectionString")))
.Mappings(cfg =>
{
cfg.FluentMappings.AddFromAssembly(Assembly.GetExecutingAssembly());
cfg.FluentMappings.Conventions.Add(AutoImport.Never());
})
.ExposeConfiguration(x =>
{
x.SetProperty("current_session_context_class", mode);
})
.BuildSessionFactory();
In Your web.config or app.config add the following within tags:
<connectionStrings>
<add name="ConnectionString" connectionString="Data Source=10.10.10.7; Initial Catalog=TestDatabase; User Id=sa; Password=9ijnhy6;"/>
</connectionStrings
Hopefully this helps.
I have some problem with enum mapping in fluent NHibernate. I know this question has been asked many times but I couldn't find any solution that worked for me. I'm newbie in NHibernate and it looks like I may have missed something simple and stupid. Here is my code.
public class DBPublication
{
public virtual int pub_id { get; set; }
public virtual PublicationStatuses status { get; set; }
...
}
public enum PublicationStatuses
{
on_moderation,
active,
...
}
public class DBPublicationMap : ClassMap<DBPublication>
{
public DBPublicationMap()
{
Table("content.publications");
Id(x => x.pub_id).GeneratedBy.Sequence("content.pub_sq");
Map(x => x.status);
...
}
}
postgres enum type
CREATE TYPE content.enum_publication_status AS ENUM('on_moderation', 'active', ...);
but when I try to save, postgres throws this
column "status" is of type content.enum_publication_status but expression is of type text
any suggestion?
Here is a working sample of configuring nhibernate to store enum field.
public class Entity
{
public virtual int id { get; set; }
public virtual SomeEnum EnumField { get; set; }
}
public enum SomeEnum
{
Value1,
Value2
}
class EntityMap : ClassMap<Entity>
{
public EntityMap()
{
Id(x => x.id).GeneratedBy.Native();
Map(x => x.EnumField);
}
}
class Program
{
static void Main(string[] args)
{
var factory = Fluently.Configure().Mappings(x => x.FluentMappings.AddFromAssemblyOf<Entity>())
.ExposeConfiguration(config => new SchemaExport(config).Create(false, true))
.Database(MsSqlConfiguration.MsSql2008.ConnectionString("Data Source=.;Initial Catalog=nhtest;Integrated Security=True"))
.BuildSessionFactory();
using (var session = factory.OpenSession())
{
using (var transaction = session.BeginTransaction())
{
var entity = new Entity();
entity.EnumField = SomeEnum.Value2;
session.Save(entity);
transaction.Commit();
}
}
}
}
In such case it is stored as strings in data base. If you want it be saved as integers, you need to change mapping for Enum field property to the following:
Map(x => x.EnumField).CustomType<int>();
Why are you creating enum types in progres? isn't this a maintenance-nightmare?
What does your configuration look like? Have you already tried using the conventions discribed here?
Looks like a simple casting error, so please consider using CustomType() / CustomSQLType() inside your mapping.
Simply add this class to your project:
public class PgEnumMapper<T> : NHibernate.Type.EnumStringType<T>
{
public override NHibernate.SqlTypes.SqlType SqlType
{
get { return new NHibernate.SqlTypes.SqlType(System.Data.DbType.Object); }
}
}
Then, you can use:
Map(x => x.status).CustomType<PgEnumMapper<PublicationStatuses>>();
I am new to NHibernate.
I am using Fluent Nhibernate and when I run a simple query I get null results.
Here is my configuration:
Fluent Configuration:
Fluently.Configure().Database(MsSqlConfiguration.MsSql2008
.ShowSql()
.ConnectionString(c => c
.FromConnectionStringWithKey("MY_DB")))
.Mappings(m =>m.FluentMappings.AddFromAssemblyOf<CsrDAL.Mappings.CsrRegistrationMap>())
.BuildSessionFactory();
Entity Class
public class Industry
{
public virtual int Id { get; private set; }
public virtual string Name { get; set; }
public virtual IList<CsrRegistration> ReferencedRegistrations { get; set; }
}
Map Class
public class IndustryMap : ClassMap<Industry>
{
public IndustryMap()
{
Table("industries");
Id(x => x.Id. "id");
Map(x => x.Name, "name");
}
}
Repository Fetch Method
public static IList<Industry> getData(CsrRegistration registration)
{
using (var session = CsrDalHelper.OpenSession())
{
using (var transaction = session.BeginTransaction())
{
try
{
IQuery q = session.CreateQuery("from Industry ind where ind.Id=1");
IList<Industry> inds =
q.List<Industry>();
return inds; // <-- This is null
}
}
}
}
Thank you in advance!
Dimitris
The problem was in session management, somewhere else in my code.
I was wrongly adding collection items to an entity outside the NH session.
As a newcomer to nhibernate, I am now studying the docs in more details.
Thank you
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();
}