【问题标题】:Generic CRUD in Entity Framework using a entity not specified实体框架中的通用 CRUD 使用未指定的实体
【发布时间】:2017-11-17 12:19:42
【问题描述】:

我正在尝试为我的项目制作通用 CRUD。但是,我使用了 DataBaseFirst,但看不到如何拥有可以继承的通用实体类。好吧,这没有任何意义,最终当我升级银行时,它必须进入所有60多个表的类并重新添加继承。我想要Entity 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 限制中使用。或者如果我使用反射而不是泛型?有什么想法吗?

【问题讨论】:

  • 你也许可以做((dynamic)e).Id == id
  • 或使用Find 方法:_dbContext.Set&lt;TEntity&gt;().AsNoTracking().Find(id)(如果它适用于 AsNoTracking...)
  • 非常感谢您回答 RandRandom 和 DavidG !!!它解决了我的问题。
  • @DavidG 我仍然不知道这是否能解决我所有的问题,但让我们试试。而不是 AsNoTracking 我可以使用 Async 方法,如下所示: return await DbContexto.Set().FindAsync(Key);

标签: c# .net entity-framework generics


【解决方案1】:

经过大量搜索,我找到了这篇葡萄牙语文章:https://msdn.microsoft.com/en-us/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();
    }
}

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-14
    • 1970-01-01
    • 1970-01-01
    • 2020-09-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多