& Lt; ABP document & gt; EntityFramework integration, abpentityframework

Source: Internet
Author: User

<ABP documentation> EntityFramework integration, abpentityframework

Document directory

 

Content of this section:

  • Nuget package
  • DbContext
  • Warehousing
    • Default Storage
    • Custom warehousing
      • Specific storage base class
      • Custom warehousing example
    • Best warehousing practices

 

You can use any ORM framework. It has built-in EntityFrame (hereinafter referred to as EF). This document will explain how to use EF in ABP. We assume you have a preliminary understanding of EF.

 

Nuget package

The Nuget package for using EF in the ABP is the Abp. entityFramework. You should add it to your application. It is best to create an EF assembly (dll) separately in your project and then rely on this package.

 

DbContext

As you know, to use EF, you should first define a DbContext for your application, as shown below:

public class SimpleTaskSystemDbContext : AbpDbContext{    public virtual IDbSet<Person> People { get; set; }    public virtual IDbSet<Task> Tasks { get; set; }    public SimpleTaskSystemDbContext()        : base("MyConnectionStringName")    {    }    protected override void OnModelCreating(DbModelBuilder modelBuilder)    {        base.OnModelCreating(modelBuilder);        modelBuilder.Entity<Person>().ToTable("StsPeople");        modelBuilder.Entity<Task>().ToTable("StsTasks").HasOptional(t => t.AssignedPerson);    }}

Apart from inheriting from AbpDbContext (not DbContext), there are no differences between the other and common DbContext. AbpDbContext has multiple overloading and you can use them as needed.

EF can map classes to database tables in an agreed way, and you don't even need to configure them unless you have customized something. In this example, we map objects to different tables and map them to the Tasks table by default Task entities. However, we can modify the object to the StsTasks table or use the data Annotation Feature to replace the configuration. I prefer smooth configuration. You can choose one as you like.

 

Warehousing

Warehouse is used to abstract data access from a higher level and view the warehouse document for more information.

 

Default Storage

Abp. EntityFramework implements default warehousing for all entities defined in your DbContext. You can directly use predefined warehousing methods without creating a storage class. For example:

public class PersonAppService : IPersonAppService{    private readonly IRepository<Person> _personRepository;    public PersonAppService(IRepository<Person> personRepository)    {        _personRepository = personRepository;    }    public void CreatePerson(CreatePersonInput input)    {                person = new Person { Name = input.Name, EmailAddress = input.EmailAddress };        _personRepository.Insert(person);    }} 

The PersonAppService constructor injects IRepository <Person> and then uses the Insert method. In this way, you can simply inject IRepository <TEntity> (or IRepository <TEntity, TPrimaryKey> ), then, use the predefined method to view the warehouse document to learn about all the predefined methods.

 

Custom warehousing

If the standard warehousing method cannot be met, you can create a custom storage class for your object.

 

Specific storage base class

ABP provides a base class EfRepositoryBase, which can easily implement warehousing. To implement the IRepository interface, your warehousing can directly inherit this class, but it is best to extend the EfRepositoryBase class. You can add shared/common methods to your warehousing. Example of a basic class for all the storages Of A SimpleTaskSystem application:

//Base class for all repositories in my applicationpublic class SimpleTaskSystemRepositoryBase<TEntity, TPrimaryKey> : EfRepositoryBase<SimpleTaskSystemDbContext, TEntity, TPrimaryKey>    where TEntity : class, IEntity<TPrimaryKey>{    public SimpleTaskSystemRepositoryBase(IDbContextProvider<SimpleTaskSystemDbContext> dbContextProvider)        : base(dbContextProvider)    {    }    //add common methods for all repositories}//A shortcut for entities those have integer Idpublic class SimpleTaskSystemRepositoryBase<TEntity> : SimpleTaskSystemRepositoryBase<TEntity, int>    where TEntity : class, IEntity<int>{    public SimpleTaskSystemRepositoryBase(IDbContextProvider<SimpleTaskSystemDbContext> dbContextProvider)        : base(dbContextProvider)    {    }    //do not add any method here, add to the class above (because this class inherits it)} 

Note: From EfRepositoryBase <SimpleTaskSystemDbContext, TEntity, TPrimaryKey> inheritance, which indicates that in our warehouse, abcuses SimpleTaskSystemDbContext.

 

Custom warehousing example

To implement a custom warehousing, you can directly inherit the specific warehousing base class in your application (such as the one we created above ).

Suppose we have a Task entity that can be assigned to a Person (entity), and a Task has a State (new, assigned, completed ...), we need to write a custom method to use a database query to obtain the Tasks list through some conditions and pre-obtained AssisgnedPerson attributes. The sample code is as follows:

public interface ITaskRepository : IRepository<Task, long>{    List<Task> GetAllWithPeople(int? assignedPersonId, TaskState? state);}public class TaskRepository : SimpleTaskSystemRepositoryBase<Task, long>, ITaskRepository{    public TaskRepository(IDbContextProvider<SimpleTaskSystemDbContext> dbContextProvider)        : base(dbContextProvider)    {    }    public List<Task> GetAllWithPeople(int? assignedPersonId, TaskState? state)    {        var query = GetAll();        if (assignedPersonId.HasValue)        {            query = query.Where(task => task.AssignedPerson.Id == assignedPersonId.Value);        }        if (state.HasValue)        {            query = query.Where(task => task.State == state);        }        return query            .OrderByDescending(task => task.CreationTime)            .Include(task => task.AssignedPerson)            .ToList();    }}

We first define ITaskRepository, then implement it, GetAll () returns IQueryable <Task>, then we use the given parameter to add some Where filter, and finally we can call ToList () to obtain the task list.

You can use the Context object in your warehousing method to directly use the ef api.

Note: You can define custom warehousing interfaces in the domain/core layer and implement interfaces in the project layer where EF is located. Therefore, you can inject this interface into any project without referencing EF.

 

Best warehousing practices

  • Use the default repository whenever possible. You can use the default repository even if you have a custom repository of a certain entity (when using the standard repository method ).
  • Create a storage base class for your custom warehousing in the application, as defined above.
  • Define the custom warehousing interface (The. Core Project in the launch template) at the domain layer, and define the custom warehousing class in the project where EF is located.

 

Kid1412 Appendix: http://www.aspnetboilerplate.com/Pages/Documents/EntityFramework-Integration

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.