c# - EntityFramework 存储库模式

标签 c# asp.net entity-framework

我的代码一直有问题。我已经开始学习 Entityframework,作为我使用 Microsoft Virtual Academy 网站的资源,他们有一个关于 Entity Framework 和 asp.net 的简短介绍。他们创建了这个采用 poco 类的存储库通用类。

public class Repository<T> where T : class
{
    private BlogDataContext context = null;
    protected DbSet<T> DbSet { get; set; }

    public Repository()
    {
        this.context = new BlogDataContext();
        DbSet = context.Set<T>();
    }

    public List<T> getAll()
    {
        return DbSet.ToList();
    }

    public T Get(int id)
    {
        return DbSet.Find(id);
    }

    public void Add(T entity)
    {
        DbSet.Add(entity);
    }

    public void Update(T entity)
    {
        context.Entry<T>(entity).State = EntityState.Modified;
    }

    public void Delete(int id)
    {
        DbSet.Remove(DbSet.Find(id));
    }

    public void SaveChanges()
    {
        context.SaveChanges();
    }
}

当您需要使用 ASP.NET 控件编辑数据库中的数据时会出现问题,到目前为止,我已经手动将数据绑定(bind)到控件并通过使用 Get(int Id) 查找数据进行更新,并且然后更新。最近我发现这个过程可以用 ObjectDataSource 控件自动化,但是更新方法会抛出一个错误

Attaching an entity of type 'CarDealership.DataLayer.UsersExtended' failed because another entity of the same type already has the same primary key value.

UsersExtended 是一个 poco 类。

最佳答案

不要使用 Get 方法,因为它将把结果实体附加到您的上下文中,并且当您将断开连接的 POCO 实体传递给具有相同方法的 Update 方法时Id,EF 将抛出该异常。

如果您的实体继承自您定义所有实体的 PK 属性的公共(public)类,例如:

public class Entity
{
   public int Id{get;set;}
}

为避免该问题,您可以将以下方法添加到您的存储库以检查该行是否存在于您的数据库中:

public class Repository<T> where T : Entity
{
     //...
     public bool Exist(int id)
    {
      return DbSet.Exist(e=>e.Id==id);
    }
}

如果您没有该设计,您可以在您的业务层中执行以下操作以检查是否相同:

var repository= new Repository<UsersExtended>();
bool exist= repository.GetAll().Exist(e=>e.Id==id);
if(exist)
{ 
   repository.Update(yourEntity)
}

另一件重要的事情,永远不要从 DbSet 调用 ToList 扩展方法,这会将您的所有表加载到内存中。把它改成这样:

public IQueryable<T> GetAll()
{
    return DbSet;
}

始终尝试在您的 BL 中查阅您的数据,并在查询结束时调用 ToList 扩展方法以仅加载所需的实体。

关于c# - EntityFramework 存储库模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35993171/

相关文章:

c# - 如何确定 Expression<Func<T, object>> 是否对 EntityFramework .Include 有效

c# - Linq 展平列表列表

c# - 将 Entity Framework 调用绑定(bind)到一个公共(public)参数,例如 UserId

c# - 如何将带有日期时间的时区解析为日期时间参数

c# - Entity Framework 4 和 Web Api 的匿名类型转换问题

c# - 返回 IQueryable 类型 : The entity or complex type '' cannot be constructed in a LINQ to Entities query

c# - Javascript 函数参数未显示在 Asp.Net MVC RouteValueDictionary 中?

asp.net - 自安装 VS 2012 以来,我遇到了间歇性 PlatformNotSupportedException

javascript - Web API Post方法不保存数据

html - 使用 % 标识符在 Asp.net 表中定义列宽