Reputation: 735
I'm working on NHibernate and when I'm testing it, I try to list all my datas in my Oracle database. But NHibernate correctly access my database but delete all my data instead of just read my data.
(I can connect to the database, there is no problem with it, it's just that it delete all my data without asking it.)
Here's my code :
NHibernateSession :
public class NHibernateSession
{
public static ISession OpenSession()
{
return CreateSessionFactory().OpenSession();
}
private static ISessionFactory CreateSessionFactory()
{
var cfg = OracleClientConfiguration.Oracle9
.ConnectionString(c =>
c.Is("DATA SOURCE=xe.world;PERSIST SECURITY INFO=True;USER ID=apismart;Password=APISMART"));
var sessionFactory = Fluently.Configure()
.Database(cfg)
.Mappings(m => m.FluentMappings.AddFromAssemblyOf<MesureMap>().ExportTo(@".\"))
.ExposeConfiguration(BuildSchema)
.BuildSessionFactory();
return sessionFactory;
}
private static void BuildSchema(NHibernate.Cfg.Configuration config)
{
new SchemaExport(config)
.Create(false, true);
}
}
}
Get in my MesuresController :
public int Get()
{
using (ISession session = NHibernateSession.OpenSession())
{
RucheRepository repo = new RucheRepository(session);
IQueryable<Ruche> result = repo.GetAll();
return result.Count();
}
}
Repository :
public class RucheRepository : IRucheRepository
{
protected ISession Session;
public RucheRepository(ISession session)
{
this.Session = session;
}
public Ruche Get(int idRuche)
{
return Session.Query<Ruche>().Where(ruche => ruche.Id == idRuche).FirstOrDefault<Ruche>();
}
public IQueryable<Ruche> GetAll()
{
return Session.Query<Ruche>();
}
}
Upvotes: 2
Views: 488
Reputation: 16389
As the accepted answer from @Rabban says, new SchemaExport(config).Create(false, true);
is the issue.
What you are doing is called code first approach where you write all your database code (specially models/entities) first. NHibernate allows creating database from this class structure.
Create
method deletes the schema if already exists and create new. Following is from documentation:
Run the schema creation script; drop script is automatically executed before running the creation script.
Have a look at syntax of Execute
in same documentation. It provides you more control over this process.
public void execute(boolean script,
boolean export,
boolean justDrop,
boolean justCreate)
Above documentation is for Hibernate (Java); but it is equally applicable for NHibernate (.net) as well.
Upvotes: 2
Reputation: 2581
The Problem comes from your BuildSchema()
method. Everytime you execute this, the database will be deleted and new created. Use this instead:
private static void BuildSchema(NHibernate.Cfg.Configuration config)
{
new SchemaUpdate(config)
.Execute(false, true);
}
It will only update your schema and not recreate it.
Upvotes: 2