开发者

NHibernate ID Private Setter (any workaround)

开发者 https://www.devze.com 2023-01-31 09:50 出处:网络
Here is a \"simplified\" class that can be mapped using NHibernate; public class Template { public virtual int Id { get; private set; }

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?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号