【发布时间】:2013-02-05 14:13:22
【问题描述】:
我在 C# 项目中使用 NHibernate,因此我有几个模型类。
让我们假设以下示例:
using System;
namespace TestProject.Model
{
public class Room
{
public virtual int Id { get; set; }
public virtual string UniqueID { get; set; }
public virtual int RoomID { get; set; }
public virtual float Area { get; set; }
}
}
到目前为止,使用 NHibernate 映射这些对象工作正常。现在我想生成一个新的 Room 对象并将其存储在数据库中。为了避免单独设置每个成员,我向模型类添加了一个新的构造函数。 在我写的虚拟会员下面:
public RoomProperty()
{
}
public RoomProperty(int pRoomId, int pArea)
{
UniqueID = Guid.NewGuid().ToString();
RoomID = pRoomId;
Area = pArea;
}
使用 FxCop 分析我的代码告诉我以下信息:
"ConstructorShouldNotCallVirtualMethodsRule"
This rule warns the developer if any virtual methods are called in the constructor of a non-sealed type. The problem is that if a derived class overrides the method then that method will be called before the derived constructor has had a chance to run. This makes the code quite fragile.
This page 也描述了为什么这是错误的,我也理解。但我不知道如何解决这个问题。
当我删除所有构造函数并添加以下方法时...
public void SetRoomPropertyData(int pRoomId, int pArea)
{
UniqueID = Guid.NewGuid().ToString();
RoomID = pRoomId;
Area = pArea;
}
.... 在调用标准构造函数后设置数据我无法启动我的应用程序,因为 NHibernate 初始化失败。它说:
NHibernate.InvalidProxyTypeException: The following types may not be used as proxies:
VITRIcadHelper.Model.RoomProperty: method SetRoomPropertyData should be 'public/protected virtual' or 'protected internal virtual'
但是将此方法设置为 virtual 与我在构造函数中设置虚拟成员时的错误相同。 如何避免这些错误(违规)?
【问题讨论】:
-
为什么不在构造时为字段而不是属性设置值?
-
@voroninp 您无法使用 NHibernate 轻松访问字段
-
因为我的模型实际上有大约 10 个成员,并且我创建了新的房间对象 qiet iften。我不想单独设置每个属性。
-
@Metalhead89 编码 sn-p(甚至 T4)不会有帮助吗?
-
我不得不承认我不知道这是什么
标签: c# constructor virtual