簡體   English   中英

使用未指定實體的Entity Framework中的通用CRUD

[英]Generic CRUD in Entity Framework using a entity not specified

我正在嘗試為我的項目制作通用CRUD。 但是,我使用了DataBaseFirst,但沒有看到如何擁有可以繼承的通用Entity類。 嗯,這沒有任何意義,最終,當我升級銀行時,它將不得不進入所有超過60個表類,並再次添加繼承。 我想要由實體Framawork生成的純實體類,例如生成的實體類。

所以我正在嘗試類似的東西:

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);
    }

但是,您可以推斷出我對未定義屬性存在此問題,因為正如我所說,我不希望有“通用實體”之類的東西。

有人知道我可以這樣做嗎? 也許它有一些實體默認使用的類,可以在where限制中使用。 或者,如果不是我使用反射而不是泛型? 任何想法?

經過大量搜索后,我找到了葡萄牙語的這篇文章: https : //msdn.microsoft.com/zh-cn/library/dn630213.aspx

在泛型類中使用以下泛型方法:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.Entity;
using Repositorio.DAL.Contexto;
namespace Repositorio.DAL.Repositorios.Base
{
public abstract class Repositorio<TEntity> : IDisposable,
   IRepositorio<TEntity> where TEntity : class
{
    BancoContexto ctx = new BancoContexto();
    public IQueryable<TEntity> GetAll()
    {
        return ctx.Set<TEntity>();
    }

    public IQueryable<TEntity> Get(Func<TEntity, bool> predicate)
    {
        return GetAll().Where(predicate).AsQueryable();
    }

    public TEntity Find(params object[] key)
    {
        return ctx.Set<TEntity>().Find(key);
    }

    public void Atualizar(TEntity obj)
    {
        ctx.Entry(obj).State = EntityState.Modified;
    }

    public void SalvarTodos()
    {
        ctx.SaveChanges();
    }

    public void Adicionar(TEntity obj)
    {
        ctx.Set<TEntity>().Add(obj);
    }

    public void Excluir(Func<TEntity, bool> predicate)
    {
        ctx.Set<TEntity>()
            .Where(predicate).ToList()
            .ForEach(del => ctx.Set<TEntity>().Remove(del));
    }

    public void Dispose()
    {
        ctx.Dispose();
    }
}

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM