<<ABP文檔>> EntityFramework 整合

來源:互聯網
上載者:User

標籤:context   code   color   name   erp   log   構造   rtc   mode   

  • Nuget 包
  • DbContext
  • 倉儲
    • 預設倉儲
    • 自訂倉儲
      • 特定的倉儲基類
      • 自訂倉儲樣本
    • 倉儲最佳實務

 

ABP可使用任何ORM架構,它已經內建了EntityFrame(以下簡稱EF),這個文檔將解釋如何在ABP裡使用EF,我們假設你對EF已經有初步的瞭解。

 

Nuget 包

在ABP裡使用EF的Nuget包是Abp.EntityFramework,你應該把它加入到你的應用裡,最好在你項目裡單獨建立一個EF程式集(dll),然後依賴該於這個包。

 

DbContext

如你所知,要使用EF,應當先為你的應用定義一個DbContext,如下所示:

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

除了從AbpDbContext繼承(不是DbContext)外,其它的與普通的DbContext沒分別,AbpDbContext有多個重載,你可以按需要使用它們。

EF可以以一種約定的方式映射類到資料庫表,你甚至不用進行配置,除非你自訂了一些東西,在這個例子裡,我們映射實體到不同的表,按預設Task實體映射到Tasks表,但我們把它修改成StsTasks表,也可以用資料註解特性代替配置。我更喜歡使用流暢的配置,你可按喜好選擇。

 

倉儲

倉儲用來抽象來自更高層的資料訪問,查看倉儲文檔擷取更多。

 

預設倉儲

Abp.EntityFramework為所有定義在你的DbContext裡的實體,實現了預設的倉儲,你不用建立倉儲類,就可以直接使用預定義的倉儲方法,例如:

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

PersonAppService構造器注入了IRepository<Person>,然後使用Insert方法,以這種方式,你可以簡單的注入IRepository<TEntity>(或IRepository<TEntity,TPrimaryKey>),然後使用預定義方法,查看倉儲文檔瞭解所有預定義方法。

 

自訂倉儲

如果標準的倉儲方法不能滿足,你可以為你的實體建立自訂的倉儲類。

 

特定的倉儲基類

ABP提供了一個基類EfRepositoryBase,可以很容易地實現倉儲。為實現IRepository介面,你的倉儲可以直接繼承該類,但最好是擴充EfRepositoryBase類,你可以在你的倉儲裡添加共用/通用的方法。一個SimpleTaskSystem應用的所有倉儲的基類樣本:

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

注意:我們從 EfRepositoryBase<SimpleTaskSystemDbContext, TEntity, TPrimaryKey>繼承,這表明在我們倉儲裡,ABP使用SimpleTaskSystemDbContext 。

 

自訂倉儲樣本

為實現一個自訂倉儲,可以直接繼承你應用裡特定的倉儲基類(如我們上面建立的)。

假設我們有一個Task實體,它可以分配給一個Person(實體),並且一個Task有一個State(new,assigned,completed...),我們需要編寫一個自訂方法,通過一些條件和預先擷取的AssisgnedPerson屬性使用一條資料庫查詢,擷取Tasks列表,範例程式碼如下:

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

我們首先定義ITaskRepository,然後實現它,GetAll()返回IQueryable<Task>,然後我們使用給定的參數添加一些Where過濾,最後我們可以調用ToList()來擷取Tasks列表。

你可以在你的倉儲方法裡使用Context對象,從而直接使用EF的API。

注意:在領域/核心層定義自訂的倉儲介面,在EF所在項目層裡實現介面,因此你可以在任何項目裡注入這個介面而不用引用EF。

 

倉儲最佳實務

  • 儘可能使用預設倉儲,即使你有一個某實體的自訂的倉儲,你也可以使用預設倉儲(當使用標準的倉儲方法)。
  • 為你的應用裡的自訂倉儲建立一個倉儲基類,如上面那樣定義。
  • 在領域層定義你自訂倉儲的介面(啟動模板裡的.Core項目),在EF所在項目裡定義自訂倉儲的類。

 

kid1412附:英文原文:http://www.aspnetboilerplate.com/Pages/Documents/EntityFramework-Integration 

<<ABP文檔>> EntityFramework 整合

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.