繁体   English   中英

如何设置要从具有现有字段的自定义类派生的Entity Framework模型?

[英]How to set up Entity Framework model to be derived from the custom class with already existing fields?

我正在使用Entity Framework 6.0和“数据库优先”方法创建应用程序。 从数据库更新模型后,我意识到基本需求模型将从BaseEntity类派生。 原因是我需要基类使用BaseEntity类访问Id属性,因为通常未指定模型类。

我当前的解决方案很简单。 根据Luke的回答,我实现了部分类架构,并直接从RootEntity派生了模型类。 实际上, RootEntity类与模型类一样具有Id属性。 编译器说CS0114警告类应重写属性。 由于模型是自动生成的,因此无法覆盖属性。

解决特定问题的最佳实践是什么? 我想实现一个清晰的体系结构,但是这种不太漂亮的模式可能会使阅读我的代码的人感到困惑。

// autogenerated EF code
public partial class Education
{
    public int Id { get; set; }
    public string Title { get; set; }
    public System.DateTime AwardDate { get; set; }
    public Nullable<int> PersonId { get; set; }

    public virtual Person Person { get; set; }
}

// the base custom class I wont others to be derived from
public class RootEntity
{
    public int Id { get; set; }
}

// partial class deriving
public partial class Education : RootEntity { }

编辑

我发现最好的解决方案是将RootEntity类作为接口IPrimary 它还不允许直接创建对象,并且提供了对所需功能的更清晰定义。

public interface IPrimary
{
    int Id { get; set; }
}

我发现最好的解决方案是将RootEntity类作为接口IPrimary释放。 它还不允许直接创建对象,并且提供了对所需功能的更清晰定义。

public interface IPrimary
{
    int Id { get; set; }
}

public partial class Education : IPrimary { }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM