문제

I am moving from CodeFirst to DatabaseFirst to map my views. In my CodeFirst approach I had a base entity like this:

public abstract class BaseEntity
{
    /// <summary>
    /// Gets or sets the entity identifier
    /// </summary>
    public virtual int Id { get; set; }
... // Some more methods here for equality checking
}

I derived all my classes from this base class, since every one of them would have an Id. So I used this BaseClass to create a generic repository. My repository looks like this:

public partial class EfRepository<T> where T : BaseEntity
{
    public readonly DemirbasContext context;
    private DbSet<T> _entities;

    /// <summary>
    /// Ctor
    /// </summary>
    /// <param name="context">Object context</param>
    public EfRepository(DemirbasContext context)
    {
        this.context = context;
    }

    public T GetById(object id)
    {
        return this.Entities.Find(id);
    }

    public void Insert(T entity)
    {
        try
        {
            if (entity == null)
                throw new ArgumentNullException("entity");

            this.Entities.Add(entity);

            this.context.SaveChanges();
        }
        catch (Exception e)
        {
        ...
        }
    }
    // Other methods here Update, Delete etc

So I was able to create repositories just by specifying the generic type paremeter like this

EfRepository<Car> carRepo = new EfRepository<Car>();

In DatabaseFirst, I cannot derive the entity classes from a base class. Is there a way to do it or what would be your suggestions?

도움이 되었습니까?

해결책

Oops, I missed code generators.

Right click on your data model (.EDM file) and click Add Code Generation Item. Choose DbContext (for simplified DbContext API).

This creates two files with .tt extensions: One for context and one for entities. If you expand the file, you will see .tt file holds all your classes there.

You can modify it as you need.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top