【发布时间】:2015-02-04 05:36:15
【问题描述】:
使用 Entity Framework 4 我想为我的对象创建一个基接口,以便基接口的属性实现为每个派生类的表中的字段(而不是在它自己的表中),然后处理派生类使用接口的类。
例如,有一个接口和一些类似的类:
public interface IBaseEntity
{
public DateTime CreatedOn { get; set; }
public string CreatedBy { get; set; }
}
public class SomeEntity : IBaseEntity
{
public int SomeEntityId { get; }
public string Name { get; set; }
public DateTime CreatedOn { get; set; }
public string CreatedBy { get; set; }
}
public class OtherEntity : IBaseEntity
{
public int OtherEntityId { get; }
public float Amount { get; set; }
public DateTime CreatedOn { get; set; }
public string CreatedBy { get; set; }
}
这将导致数据库中有两个表,SomeEntity 和 OtherEntity,每个表都有四个字段。 SomeEntity 有 SomeEntityId、Name、CreatedOn 和 CreatedBy,OtherEntity 有 OtherEntityId、Amount、CreatedOn 和 CreatedBy。没有 IBaseEntity 表。
我希望在设计器中看到这一点,因为 IBaseEntity 是一个具有 CreatedOn 和 CreatedBy 属性的抽象实体,而两个具体实体只有它们的非派生属性 - 所以 SomeEntity 只有 SomeEntityId 和 Name。具体实体与抽象实体之间存在继承关系。
然后我想在保存这些对象时为这些对象设置automatic column updates,如下所示:
namespace MyModel
{
public partial class MyEntities
{
partial void OnContextCreated()
{
this.SavingChanges += new EventHandler(OnSavingChanges);
}
private static void OnSavingChanges(object sender, EventArgs e)
{
var stateManager = ((MyEntities)sender).ObjectStateManager;
var insertedEntities = stateManager.GetObjectStateEntries(EntityState.Added);
foreach (ObjectStateEntry stateEntryEntity in insertedEntities)
{
if (stateEntryEntity.Entity is IBaseEntity)
{
IBaseEntity ent = (IBaseEntity)stateEntryEntity.Entity;
ent.CreatedBy = HttpContext.Current.User.Identity.Name;
ent.CreatedOn = DateTime.Now;
}
}
}
}
}
我刚开始使用实体框架,看起来这应该可以很容易地完成,但是如何实际实现它却让我无法理解。我在这里偏离轨道还是在 Entity Framework 4 中可能发生这种事情? Table Per Concrete Type Strategy 似乎是解决方案,但我无法让它发挥作用。
【问题讨论】: