我将 NHibernate 用于我的 C# 项目,因此我有几个模型类。
让我们假设以下示例:
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.
该页面还描述了为什么这是错误的,我也理解。但我不知道如何解决这个问题。
当我删除所有构造函数并添加以下方法时......
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 与我在构造函数中设置虚拟成员时的错误相同。我怎样才能避免这些错误(违规)?