Sheldor the conqueror
Sheldor the conqueror

Reputation: 1207

Working with legacy databases and SchemaAction in Fluent NHibernate

I have two classes:

public class User
{
  public virtual int Id { get; set; }
  public virtual string Name { get; set; }
}

public class Report
{
  public virtual int Id { get; set; }
  public virtual string Name { get; set; }
  public virtual User User { get; set; }
}

... where class User already is an existing table in the database. Now, I want to add Report as a table to the database, and for this I plan to use Fluent NHibernate. I'm mapping both User and Report, since I want User to be accessible from the Report class. There is a one-to-many relationship between User and Report.

I already have tests which export SQL scripts to the database and User is included in these. Now I also want to export the scripts generated by FNH but I don't want FNH to generate User, since it's already in the database.

Therefore, I can specify SchemaAction.None() in the mapping for User. This makes FNH not generate script for User, only for Result. The only problem is, no foreign key is generated in the table Report. How can I make FNH not export generated script for User but still export the foreign key for the table Report?

If I simply not specify SchemaAction, tables User and Report are created and the foreign key in Report is generated.

Upvotes: 0

Views: 474

Answers (1)

Firo
Firo

Reputation: 30813

  1. copy the old/existing schema into a new database
  2. create an NHibernate Configuration with your mappings and the existing database
  3. use this code to write the update script into a file

    using (var file = new StreamWriter("SchemaUpdateScript.txt"))
    {
        new SchemaUpdate(config).Execute(file.WriteLine, false);
    }
    
  4. double check that the update script really does what you want

Point 1. is optional. I would strongly advice against using SchemaUpdate directly in production environment.

Upvotes: 1

Related Questions