【问题标题】:Interface inheritance in Entity Framework实体框架中的接口继承
【发布时间】: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 似乎是解决方案,但我无法让它发挥作用。

【问题讨论】:

标签: entity-framework-4


【解决方案1】:

界面不会成为实体模型的一部分,也无法在设计器中显示。但是您可以通过部分类添加它,然后您的代码将起作用。我们实际上为此使用了 T4 模板,但手动完成时也可以正常工作。

【讨论】:

  • 哇,旧德尔福时代的似曾相识!也许我问错了问题,而界面不是解决问题的方法。我想要的是一种继承方式,这样我的表就知道它们必须实现父级的字段。所以最初他们有 CreatedBy 和 CreatedOn 但我可以将其他字段添加到父级,比如 ModifiedBy 和 ModifiedOn,并且所有后代表现在都知道也实现这些字段。能够通过接口使用所有类当然也是有益的,但最初我想要某种表格模板。
【解决方案2】:

嗯,这已经很老了,但我想我会提到你可以通过抽象类以及接受的回答者建议的方式来完成原始发布者想要的。

【讨论】:

  • 这是真的,但由于 C# 不支持类的多重继承,因此用途有限。在这种情况下,OP 正在为审计数据创建一个接口,这不太可能是您希望层次结构中的每个类都支持的东西。
  • 您不能同时从多个类继承的“多重继承”,但是您当然可以拥有多个继承级别并以这种方式完成 OP 想要的。有时会采用接受的答案建议的方式(有时我会这样做),有时会使用抽象类。工具箱中只有两个不同的工具:)
猜你喜欢
  • 2016-07-10
  • 2011-05-19
  • 2010-10-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-05-08
相关资源
最近更新 更多