ASP.NET 5 MVC 6 Generic Repository Pattern

百般思念 提交于 2019-12-03 08:26:04

Entity Framework 7 Beta 8 doesn't come with the Find Method. It will probably be added before the final release.

You will have to use the the FirstOrDefault method instead until that happens

public virtual T GetById(int id)
{
    return this.Entities.FirstOrDefault(x => x.Id == id);
}

Because Id property will not be recognized you'll have to add an interface and make your repository implement it.

public interface IEntity
{
     int Id { get; set; }
}

e.g.

 public class GenericRepository<T> : IGenericRepository<T> where T: class, IEntity

From the github issues list. EF7 does not perform automatic data validation so DbEntityValidationException does not exist in EF7.

Take note: EF7 is not a update of EF but a rewrite.

In Entity Framework 7 IDbSet itself represents an implementation of Repository pattern.

/// <summary>
///     A DbContext instance represents a session with the database and can be used to query and save
///     instances of your entities. DbContext is a combination of the Unit Of Work and Repository patterns.
/// </summary>

Source: GitHub EntityFramework7 repo, DbContext.cs 24-27 line

And DBContext it's implementation of UnitOfWork

On the contrary of firste's answer, I'm not confident by using FirstOrDefault, cause it will generates a SELECT TOP 1 [...].

In many cases, the Id should be unique, but sometimes you can have bad designed Db's. If not, your application should throws an exception (that's what we're looking after).

So, until EF7 implements a Find() method, I strongly suggest using SingleOrDefault() :

public virtual T GetById(int id)
{
    return this.Entities.SingleOrDefault(x => x.Id == id);
}

Like that, you add an application control to verify that Id should be unique, taking no cares if the Db is correctly done or not. It add another level of security to your business.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!