我使用designer从数据库导入了一个表,然后我编辑了相应的cs文件,为模型添加了额外的功能(正是由于这个原因,这是部分)。现在我想出了一些关于如何使该功能更可重用的想法,并将其打包到基类中(因此在上下文代码中我有partial class Foo : BaseClass
)。我让分部类继承基类,一切都很好…除了局部方法。
OnCreated
方法)。我在基类中添加了一个OnCreated
方法,并在其中放置了一个断点,但它从未被击中。
我能否以某种方式使部分类从非部分父类获取部分方法的代码,或者我在这里做错了什么?
背景:我有一个特定的结构(列包含作者的id,用户的id谁是最后一个修改创建和更新日期的记录和日期)出现在多个表中,我试图定义大多数代码来处理在一个地方在我的项目。它涉及到对关联用户的统一访问,我通过在基类中定义关联(基本上是这样,但做了很少的修改)实现了这一点。到目前为止,它似乎工作得很好,除了我应该在生成的类的构造函数中为存储变量分配默认值( this._SomeVariable = default(EntityRef<SomeModel>)
)。然而,修改生成的代码是没有意义的,因为当文件重新生成时,所有的更改都将丢失。因此,下一个最好的事情是实现OnCreated
部分方法,它在生成类的末尾运行。我可以在非生成的cs文件中为我的模型实现,但我宁愿把它放在与所有类似模型共享的基类中。
下面是一些简单的代码,使它更清楚:
生成的代码:
partial class Foo
{
public Foo()
{
// does some initialization here
this.OnCreated();
}
partial void OnCreated();
}
Foo
扩展代码:
partial class Foo : BaseClass // Thanks to this I can use the uniform JustSomeModel association
{
// This code here would run if it was uncommented
// partial void OnCreated() {}
// However I'd rather just have the code from base.OnCreated()
// run without explicitly calling it
}
基类:
public class BaseClass
{
protected EntityRef<SomeModel> _SomeVariable;
[Association(Name = "FK_SomeModel", Storage = "_SomeVariable", ThisKey = "SomeModelId", OtherKey = "Id", IsForeignKey = true)]
public SomeMode JustSomeModel
{
get
{
return this._SomeVariable.Entity;
}
}
// This never runs
public void OnCreated()
{
this._SomeVariable = default(EntityRef<SomeModel>)
}
}
我现在能想到的最好的解决方案是这样做:
partial class Foo : BaseClass
{
partial void OnCreated()
{
base.OnCreated(); // Haven't really tested this yet
}
}
然而,这意味着我将不得不将这段代码添加到我使用的BaseClass
继承的每个模型中,我宁愿避免它。
根据Eugene Podskal发布的信息,我可以假设这不能做到,我最好的选择是实现部分方法并在其中调用基方法。
partial class Foo : BaseClass
{
partial void OnCreated()
{
base.OnCreated();
}
}