简体   繁体   中英

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

I am creating an application using Entity Framework 6.0 and Database-First approach. After I updated model from the database, I realised the essential need models to be derived from a BaseEntity class. The reason is that I need the base class to access the Id property using the BaseEntity class because the model class is often not specified.

My current solution is simple. According to Luke answer I implemented the partial class schema and directly derived a model class from RootEntity . In fact, the RootEntity class has the Id property as the model classes do. The compiler says CS0114 warning that classes should override properties. Since the model is autogenerated it cannot override properties.

What is the best practice to solve the particular issue? I'd like to implement a cleared architecture but this unpretty pattern may confuse anyone who reads my code.

// 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 { }

EDIT :

The best solution I've found is to release the RootEntity class as an interface IPrimary . It also doesn't allow to directly create an object and provides a clearer definition of the required functionality.

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

The best solution I've found is to release the RootEntity class as an interface IPrimary. It also doesn't allow to directly create an object and provides a clearer definition of the required functionality.

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

public partial class Education : IPrimary { }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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