使用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和名称。具体实体和抽象实体之间存在继承关系。
那么我想要
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;
}
}
}
}
}
我刚开始使用实体框架,看起来这应该可以很容易地完成,但是如何实际实现它却让我感到很困惑。我是不是偏离了轨道,还是在实体框架4中可能出现这种情况?每种具体类型策略的表似乎是解决方案,但我还没能让它工作。