CRUD Generic in Entity Framework with entity not specified

1

I'm trying to make a Generic CRUD for my project. However as I used DataBaseFirst I do not see how to have a generic class of Entity that can be inherited. Well it does not make the slightest sense, eventually when I upgrade the bank, it would have to go into all the more than 60 classes of the tables and add the inheritance again. I want the Entity classes that the Entity Framawork generated as pure as they were generated.

So I'm trying something like:

ButasyoucanseeIhavethispropertyproblemnotbeingdefined,sinceasIsaidIdonotwanttohaveanythinglikea"General Entity".

Does anyone know of any way to achieve this? Type has some class that Entity uses beneath the wads that can be used in the where constraint. Or maybe if instead of Generics I used Reflection? Any idea?

Edited: Added Code.

public class DaoEF<TEntity> : IDaoEF<TEntity>
    where TEntity : class
{
    public GPSdEntities _dbContext { get; set; } = new GPSdEntities();


    public async Task<TEntity> GetById(int id)
    {
        return await _dbContext.Set<TEntity>()
                    .AsNoTracking()
                    .FirstOrDefaultAsync(e => e.Id == id);
    }
    
asked by anonymous 17.11.2017 / 13:07

1 answer

3

First, CRUD generic Entity Framework already has, it is called DbSet<T> .

Second point, I see that you want to abuse AsNoTracking , this will bring you more problems than I get, so I advise you not to encapsulate it, let the developer decide when to use it.

Third, if all you need is to write reusable queries, then extend DbContext . As you are doing, you will have multiple Contexts working in the same unit of work.

public static class EFExtensions<TEntity> where TEntity : class
{
    public static async Task<TEntity> GetById<TEntity>(this GPSdEntities context, int id)
    {
        return await _dbContext.Set<TEntity>()
            .AsNoTracking()
            .FirstOrDefaultAsync(e => e.Id == id);
    }
}

Now answering your question, the automatically generated classes are all partial, so let's say you have a class like the following:

public partial class MinhaClass
{
    public string Prop1 { get; set; }
}

You can define in a second file the complementation of this class.:

public partial class MinhaClass : IDisposable
{
    public void Dispose()
    { 

    }
}

You would already have to create this file / class if you need to add some attribute to the generated properties.:

public class MinhaClassMeta
{
    [Display(Name = "Propriedade 01")]
    public string Prop1 { get; set; }
}


[MetadataType(typeof(MinhaClassMeta))]
public partial class MinhaClass : IDisposable
{
    public void Dispose()
    { 

    }
}
    
17.11.2017 / 13:28