0

Here is a "simplified" class that can be mapped using NHibernate;

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

As the ID field has a private setter we can no longer have code like this in our application where we manually set the ID field;

var DefaultTemplate = new Template { ID = (int)TemplateEnum.Default, Name = "Default" }

Here we are manually creating a DefaultTemplate object that we can assign to anything. Other Templates are manually created by users and saved to the database.

Any ideas how we can still achieve this kind of functionality?

Please note: C# Winforms, .NET 3.5 and we don't want to use Reflection for this.

Piere
  • 83
  • 1
  • 4
  • I believe your options are: 1) make the setter public, 2) use reflection. – R. Martinho Fernandes Dec 21 '10 at 12:36
  • if we make the setter public, will NHibernate still work without issue? – Piere Dec 21 '10 at 12:40
  • 1
    If your mapping allows the Id to be settable then yes it will work fine. But I would extend Template to have a DefaultTemplate which extends the map to allow the Id to be settable so Template and DefaultTemplate can be handled separately. – Phill Dec 21 '10 at 12:44

2 Answers2

1

I would do it like this, if feasible:

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

  public static readonly Template Default = new Template() {ID = (int)TemplateEnum.Default, Name = "Default"};
}

Then, you can always 'get' the default template, without having to instantiate it from the outside of the Template class:

Template t = Template.Default;
Frederik Gheysels
  • 56,135
  • 11
  • 101
  • 154
0

Use protected instead of private.

Edit: Wait, I miss-read your question, you want it public so you can set it?

Why do you want to manually assign the value?

You could have a constructor that takes the Id. Then do:

var DefaultTemplate = new Template((int)TemplateEnum.Default) { Name = "Default" }

But still, it's either public, or reflection. Why do you need to manually set the value?

Phill
  • 18,398
  • 7
  • 62
  • 102
  • Thanks Phill. We can assign a "default" template in addition to any of the templates saved by a user in the database. For example the ID for a "default" template is -1 which is internal to the application and any ID's assigned by the database (now NHibernate) will always be positive. – Piere Dec 21 '10 at 12:39