NHibernate ID Private Setter (any workaround)
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 = "Defaul开发者_StackOverflow中文版t" }
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.
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;
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?
精彩评论