NHibernate ID Private Setter(任何解决方法)

发布于 2024-10-08 15:03:53 字数 489 浏览 0 评论 0原文

这是一个可以使用 NHibernate 映射的“简化”类;

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

由于 ID 字段有一个私有设置器,我们不能再在应用程序中手动设置 ID 字段,这样的代码;

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

在这里,我们手动创建一个可以分配给任何内容的 DefaultTemplate 对象。其他模板由用户手动创建并保存到数据库中。

我们有什么想法仍然可以实现这种功能吗?

请注意:C# Winforms、.NET 3.5,我们不想为此使用反射。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

邮友 2024-10-15 15:03:53

如果可行的话,我会这样做:

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"};
}

然后,您始终可以“获取”默认模板,而不必从 Template 类的外部实例化它:

Template t = Template.Default;

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;
掀纱窥君容 2024-10-15 15:03:53

使用受保护的而不是私有的。

编辑:等等,我漏读了您的问题,您希望将其公开以便可以设置吗?

为什么要手动赋值呢?

您可以有一个采用 Id 的构造函数。然后做:

var DefaultTemplate = new Template((int)TemplateEnum.Default) { Name = "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?

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文