使用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,看起来这应该能够相当容易地完成,但是如何实际实现它正在逃避我.我在这里偏离轨道还是在Entity Framework 4中可以做到这一点?每个混凝土类型策略表似乎是解决方案但我无法使其工作.
界面不是实体模型的一部分,无法在设计器中显示.但是你可以通过局部类添加它,然后你的代码就可以了.我们实际上使用了T4模板,但是手动完成时也能正常工作.