diff --git a/docs/Data-Transfer-Objects.md b/docs/Data-Transfer-Objects.md new file mode 100644 index 0000000000..b0d80246f7 --- /dev/null +++ b/docs/Data-Transfer-Objects.md @@ -0,0 +1,3 @@ +## Data Transfer Objects + +TODO \ No newline at end of file diff --git a/docs/Entities.md b/docs/Entities.md new file mode 100644 index 0000000000..1777d9829b --- /dev/null +++ b/docs/Entities.md @@ -0,0 +1,169 @@ +## Entities + +Entities are one of the core concepts of DDD (Domain Driven Design). Eric Evans describe it as "*An object that is not fundamentally defined by its attributes, but rather by a thread of continuity and identity*". + +An entity is generally mapped to a table in a relational database. + +### Entity Class + +Entities are derived from `Entity` class as shown below: + +```C# +public class Person : Entity +{ + public string Name { get; set; } + + public DateTime CreationTime { get; set; } + + public Person() + { + CreationTime = DateTime.Now; + } +} +``` + +> If you do not want derive your entity from the base `Entity` class, you can directly implement `IEntity` interface. + +`Entity` class just defines an `Id` property with the given primary **key type**, which is `int` in the sample above. It can be other types like `string`, `Guid`, `long` or whatever you need. + +Entity class also overrides the **equality** operator (==) to easily check if two entities are equal (they are equals if they are same entity type and their Ids are equals). + +#### Entities with Composite Keys + +Some entities may need to have **composite keys**. In that case, you can derive your entity from the non-generic `Entity` class. Example: + +````C# +public class UserRole : Entity +{ + public Guid UserId { get; set; } + + public Guid RoleId { get; set; } + + public DateTime CreationTime { get; set; } + + public Phone() + { + + } +} +```` + +For the example above, the composite key is composed of `UserId` and `RoleId`. For a relational database, it is the composite primary key of the related table. + +Notice that you also need to define keys of the entity in your **object-to-relational mapping** (ORM) configuration. + +> Composite primary keys has a restriction with repositories. Since it has not known Id property, you can not use `IRepository` for these entities. However, you can always use `IRepository`. See repository documentation (TODO: link) for more. + +### AggregateRoot Class + +"*Aggregate is a pattern in Domain-Driven Design. A DDD aggregate is a cluster of domain objects that can be treated as a single unit. An example may be an order and its line-items, these will be separate objects, but it's useful to treat the order (together with its line items) as a single aggregate.*" (see the [full description](http://martinfowler.com/bliki/DDD_Aggregate.html)) + +`AggregateRoot` class extends the `Entity` class. So, it also has an `Id` property by default. + +> Notice that ABP creates default repositories only for aggregate roots by default. However, it's possible to include all entities. See repository documentation (TODO: link) for more. + +ABP does not force you to use aggregate roots, you can only use the `Entity` class as defined before. However, if you want to implement DDD and want to create aggregate root classes, there are some best practices you may want to consider: + +* An aggregate root is responsible to preserve it's own integrity. This is also true for all entities, but aggregate root has responsibility for it's sub entities too. So, the aggregate root always be in a valid state. +* An aggregate root can be referenced by it's Id. Do not reference it by navigation property. +* An aggregate root is treated as a single unit. It's retrieved and updated as a single unit. It's generally considered as a transaction boundary. +* Work with sub-entities over the aggregate root, do not modify them independently. + +#### Aggregate Example + +This is a full sample of an aggregate root with a related sub-entity collection: + +````C# +public class Order : AggregateRoot +{ + public virtual string ReferenceNo { get; protected set; } + + public virtual int TotalItemCount { get; protected set; } + + public virtual DateTime CreationTime { get; protected set; } + + public virtual List OrderLines { get; protected set; } + + protected Order() + { + + } + + public Order(Guid id, string referenceNo) + { + Check.NotNull(referenceNo, nameof(referenceNo)); + + Id = id; + ReferenceNo = referenceNo; + + OrderLines = new List(); + } + + public void AddProduct(Guid productId, int count) + { + if (count <= 0) + { + throw new ArgumentException( + "You can not add zero or negative count of products!", + nameof(count) + ); + } + + var existingLine = OrderLines.FirstOrDefault(ol => ol.ProductId == productId); + + if (existingLine == null) + { + OrderLines.Add(new OrderLine(this.Id, productId, count)); + } + else + { + existingLine.ChangeCount(existingLine.Count + count); + } + + TotalItemCount += count; + } +} + +public class OrderLine : Entity +{ + public virtual Guid OrderId { get; protected set; } + + public virtual Guid ProductId { get; protected set; } + + public virtual int Count { get; protected set; } + + protected OrderLine() + { + + } + + internal OrderLine(Guid orderId, Guid productId, int count) + { + OrderId = orderId; + ProductId = productId; + Count = count; + } + + internal void ChangeCount(int newCount) + { + Count = newCount; + } +} +```` + +> If you do not want derive your aggregate root from the base `AggregateRoot` class, you can directly implement `IAggregateRoot` interface. + +`Order` is an **aggregate root** with `Guid` type `Id` property. It has a collection of `OrderLine` entities. `OrderLine` is another entity with a composite primary key (`OrderLine` and ` ProductId`). + +While this example may not implement all best practices of an aggregate root, it follows some good practices: + +* `Order` has a public constructor that takes **minimal requirements** to construct an `Order` instance. So, it's not possible to create an order without an id and reference number. The **protected/private** constructor is only necessary to **deserialize** object while reading from a data source. +* `OrderLine` constructor is internal, so it only allows to be created by the domain layer. It's used inside of `Order.AddProduct` method. +* `Order.AddProduct` implements the business rule to add a product to an order. +* All properties have `protected` setters. This is to prevent entity from arbitrary changes from outside of the entity. For instance, it would be dangerous to set `TotalItemCount` without adding a new product to the order. It's value is maintained by the `AddProduct` method. + +ABP does not force you to apply any DDD rule or pattern. However, it tries to make it possible and easier when you want to apply. The documentation also follows this principle. + +#### Aggregate Roots with Composite Keys + +While it's not common (and not suggested) for aggregate roots, it's possible to define composite keys just as defined for entities above. Use non-generic `AggregateRoot` base class in that case. \ No newline at end of file diff --git a/docs/Index.md b/docs/Index.md index 370f40179b..0a8d8ea6c3 100644 --- a/docs/Index.md +++ b/docs/Index.md @@ -12,7 +12,19 @@ * Basics * Plug-In Modules * Best Practices +* Domain Driven Design + * Domain Layer + * [Entities & Aggregate Roots](Entities.md) + * Value Objects + * [Repositories](Repositories.md) + * Domain Services + * Specifications + * Domain Events + * Application Layer + * Application Services + * Data Transfer Objects + * Unit Of Work * Data Access * [Entity Framework Core Integration](Entity-Framework-Core.md) -* Presentation (User Interface) +* Presentation / User Interface * Localization \ No newline at end of file diff --git a/docs/Object-To-Object-Mapping.md b/docs/Object-To-Object-Mapping.md new file mode 100644 index 0000000000..b0d80246f7 --- /dev/null +++ b/docs/Object-To-Object-Mapping.md @@ -0,0 +1,3 @@ +## Data Transfer Objects + +TODO \ No newline at end of file diff --git a/docs/Repositories.md b/docs/Repositories.md new file mode 100644 index 0000000000..969b0c70f6 --- /dev/null +++ b/docs/Repositories.md @@ -0,0 +1,117 @@ +## Repositories + +"*Mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects*" (Martin Fowler). + +Repositories, in practice, are used to perform database operations for domain objects (see [Entities](Entities.md)). Generally, a separated repository is used for each **aggregate root** or entity. + +### Generic Repositories + +ABP can provide a **default generic repository** for each aggregate root or entity. You can [inject](Dependency-Injection.md) `IRepository` into your service and perform standard **CRUD** operations. Example usage: + +````C# +public class PersonAppService : ApplicationService +{ + private readonly IRepository _personRepository; + + public PersonAppService(IRepository personRepository) + { + _personRepository = personRepository; + } + + public async Task Create(CreatePersonDto input) + { + var person = new Person { Name = input.Name, Age = input.Age }; + + await _personRepository.InsertAsync(person); + } + + public List GetList(string nameFilter) + { + var people = _personRepository + .Where(p => p.Name.Contains(nameFilter)) + .ToList(); + + return people + .Select(p => new PersonDto {Id = p.Id, Name = p.Name, Age = p.Age}) + .ToList(); + } +} +```` + +In this example; + +* `PersonAppService` simply injects `IRepository` in it's constructor. +* `Create` method uses `InsertAsync` to save a newly created entity. +* `GetList` method uses the standard LINQ `Where` and `ToList` methods to filter and get a list of people from the data source. + +> The example above uses hand-made mapping between [entities](Entities.md) and [DTO](Data-Transfer-Objects.md)s. See [object to object mapping document](Object-To-Object-Mapping.md) for an automatic way of mapping. + +Generic Repositories provides some standard CRUD features out of the box: + +* Providers `Insert` method to save a new entity. +* Providers `Update` and `Delete` methods to update or delete an entity by entity object or it's id. +* Provides `Delete` method to delete multiple entities by a filter. +* Implements `IQueryable`, so you can use LINQ and extension methods like `FirstOrDefault`, `Where`, `OrderBy`, `ToList` and so on... +* Have **sync** and **async** versions for all methods. + +#### Generic Repository without a Primary Key + +If your entity does not has an Id primary key (it may have a composite primary key for instance) then you can not use the `IRepository` defined above. In that case, you can inject and use `IRepository` for your entity. + +> `IRepository` has a few missing methods those normally works with the `Id` property of an entity. Because of the entity has no `Id` property in that case, these methods are not available. One example is the `Get` method that gets an id and returns the entity with given id. However, you can still use `IQueryable` features to query entities by standard LINQ methods. + +### Basic Repositories + +Standard `IRepository` interface extends standard `IQueryable` and you can freely query using standard LINQ methods. However, some ORM providers or database systems may not support standard `IQueryable` interface. + +ABP provides `IBasicRepository` and `IBasicRepository` interfaces to support such scenarios. You can extend these interfaces (and optionally derive from `BasicRepositoryBase`) to create custom repositories for your entities. + +Depending to `IBasicRepository` but not depending to `IRepository` has an advantage to make possible to work with all data sources even if they don't support `IQueryable`. But major vendors, like Entity Framework, NHibernate or MongoDb already support `IQueryable`. + +So, working with `IRepository` is the **suggested** way for typical applications. But reusable module developers may consider `IBasicRepository` to support wide range of data sources. + +### Custom Repositories + +Default generic repositories will be sufficient for most cases. However, you may need to create a custom repository class for your entity. + +#### Custom Repository Example + +ABP does not force you to implement any interface or inherit from any base class for a repository. It can be just a simple POCO class. However, it's suggested to inherit existing repository interface and classes to make your work easier and get the standard methods out of the box. + +##### Custom Repository Interface + +First, define an interface in your domain layer: + +```c# +public interface IPersonRepository : IRepository +{ + Task FindByNameAsync(string name); +} +``` + +This interface extends `IRepository` to take advantage of pre-built repository functionality. + +##### Custom Repository Implementation + +A custom repository tightly depends on the data access tool you are using. In this example, we will use Entity Framework Core: + +````C# +public class PersonRepository : EfCoreRepository, IPersonRepository +{ + public PersonRepository(IDbContextProvider dbContextProvider) + : base(dbContextProvider) + { + + } + + public async Task FindByNameAsync(string name) + { + return await DbContext.Set() + .Where(p => p.Name == name) + .FirstOrDefaultAsync(); + } +} +```` + +You can directly access to the data access provider (`DbContext` in this case) to perform operations. See [entity framework integration document](Entity-Framework-Core.md) for more about custom repositories based on EF Core. + diff --git a/src/AbpDesk/AbpDesk.Application/AbpDesk/Tickets/TicketAppService.cs b/src/AbpDesk/AbpDesk.Application/AbpDesk/Tickets/TicketAppService.cs index dcc897d516..3767772a21 100644 --- a/src/AbpDesk/AbpDesk.Application/AbpDesk/Tickets/TicketAppService.cs +++ b/src/AbpDesk/AbpDesk.Application/AbpDesk/Tickets/TicketAppService.cs @@ -12,11 +12,11 @@ namespace AbpDesk.Tickets { public class TicketAppService : ApplicationService, ITicketAppService { - private readonly IQueryableRepository _ticketRepository; + private readonly IRepository _ticketRepository; private readonly IAsyncQueryableExecuter _asyncQueryableExecuter; public TicketAppService( - IQueryableRepository ticketRepository, + IRepository ticketRepository, IAsyncQueryableExecuter asyncQueryableExecuter) { _ticketRepository = ticketRepository; diff --git a/src/AbpDesk/AbpDesk.ConsoleDemo/AbpDesk/ConsoleDemo/BlogPostLister.cs b/src/AbpDesk/AbpDesk.ConsoleDemo/AbpDesk/ConsoleDemo/BlogPostLister.cs index 5d664d7a0d..a7be728c40 100644 --- a/src/AbpDesk/AbpDesk.ConsoleDemo/AbpDesk/ConsoleDemo/BlogPostLister.cs +++ b/src/AbpDesk/AbpDesk.ConsoleDemo/AbpDesk/ConsoleDemo/BlogPostLister.cs @@ -9,11 +9,11 @@ namespace AbpDesk.ConsoleDemo { public class BlogPostLister : ITransientDependency { - private readonly IQueryableRepository _blogPostRepository; + private readonly IRepository _blogPostRepository; private readonly IGuidGenerator _guidGenerator; public BlogPostLister( - IQueryableRepository blogPostRepository, + IRepository blogPostRepository, IGuidGenerator guidGenerator) { _blogPostRepository = blogPostRepository; diff --git a/src/AbpDesk/AbpDesk.ConsoleDemo/AbpDesk/ConsoleDemo/UserLister.cs b/src/AbpDesk/AbpDesk.ConsoleDemo/AbpDesk/ConsoleDemo/UserLister.cs index 51a5a8f1e0..2aa8f30245 100644 --- a/src/AbpDesk/AbpDesk.ConsoleDemo/AbpDesk/ConsoleDemo/UserLister.cs +++ b/src/AbpDesk/AbpDesk.ConsoleDemo/AbpDesk/ConsoleDemo/UserLister.cs @@ -11,11 +11,11 @@ namespace AbpDesk.ConsoleDemo public class UserLister : ITransientDependency { private readonly IdentityUserManager _userManager; - private readonly IQueryableRepository _userRepository; + private readonly IRepository _userRepository; public UserLister( IdentityUserManager userManager, - IQueryableRepository userRepository) + IRepository userRepository) { _userManager = userManager; _userRepository = userRepository; diff --git a/src/AbpDesk/AbpDesk.MongoBlog/AbpDesk/Blogging/AbpDeskMongoBlogModule.cs b/src/AbpDesk/AbpDesk.MongoBlog/AbpDesk/Blogging/AbpDeskMongoBlogModule.cs index 8e5df159d1..7636bb19b4 100644 --- a/src/AbpDesk/AbpDesk.MongoBlog/AbpDesk/Blogging/AbpDeskMongoBlogModule.cs +++ b/src/AbpDesk/AbpDesk.MongoBlog/AbpDesk/Blogging/AbpDeskMongoBlogModule.cs @@ -1,4 +1,5 @@ -using System.Linq; +using System; +using System.Linq; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Volo.Abp; @@ -46,7 +47,7 @@ namespace AbpDesk.Blogging using (var uow = scope.ServiceProvider.GetRequiredService().Begin()) { - var blogPostRepository = scope.ServiceProvider.GetRequiredService>(); + var blogPostRepository = scope.ServiceProvider.GetRequiredService>(); if (blogPostRepository.Any()) { logger.LogInformation($"No need to seed database since there are already {blogPostRepository.Count()} blog posts!"); diff --git a/src/AbpDesk/AbpDesk.MongoBlog/AbpDesk/Blogging/BlogPost.cs b/src/AbpDesk/AbpDesk.MongoBlog/AbpDesk/Blogging/BlogPost.cs index 1ead1ae0d5..004b14843c 100644 --- a/src/AbpDesk/AbpDesk.MongoBlog/AbpDesk/Blogging/BlogPost.cs +++ b/src/AbpDesk/AbpDesk.MongoBlog/AbpDesk/Blogging/BlogPost.cs @@ -6,7 +6,7 @@ using Volo.Abp.Domain.Entities; namespace AbpDesk.Blogging { - public class BlogPost : AggregateRoot + public class BlogPost : AggregateRoot { public virtual string Title { get; protected set; } diff --git a/src/AbpDesk/AbpDesk.MongoBlog/AbpDesk/Blogging/BlogPostComment.cs b/src/AbpDesk/AbpDesk.MongoBlog/AbpDesk/Blogging/BlogPostComment.cs index f8298acc4d..b352faa92a 100644 --- a/src/AbpDesk/AbpDesk.MongoBlog/AbpDesk/Blogging/BlogPostComment.cs +++ b/src/AbpDesk/AbpDesk.MongoBlog/AbpDesk/Blogging/BlogPostComment.cs @@ -1,9 +1,10 @@ -using JetBrains.Annotations; +using System; +using JetBrains.Annotations; using Volo.Abp.Domain.Entities; namespace AbpDesk.Blogging { - public class BlogPostComment : Entity + public class BlogPostComment : Entity { [NotNull] public virtual string Name { get; protected set; } diff --git a/src/AbpDesk/AbpDesk.MongoBlog/Areas/Blog/Controllers/PostsController.cs b/src/AbpDesk/AbpDesk.MongoBlog/Areas/Blog/Controllers/PostsController.cs index 64e0dcf640..dcd44efa0f 100644 --- a/src/AbpDesk/AbpDesk.MongoBlog/Areas/Blog/Controllers/PostsController.cs +++ b/src/AbpDesk/AbpDesk.MongoBlog/Areas/Blog/Controllers/PostsController.cs @@ -1,4 +1,5 @@ -using System.Threading.Tasks; +using System; +using System.Linq; using AbpDesk.Blogging; using Microsoft.AspNetCore.Mvc; using Volo.Abp.AspNetCore.Mvc; @@ -9,16 +10,16 @@ namespace Areas.Blog.Controllers [Area("Blog")] public class PostsController : AbpController { - private readonly IQueryableRepository _blogPostRepository; + private readonly IRepository _blogPostRepository; - public PostsController(IQueryableRepository blogPostRepository) + public PostsController(IRepository blogPostRepository) { _blogPostRepository = blogPostRepository; } - public async Task Index() + public ActionResult Index() { - var posts = await _blogPostRepository.GetListAsync(HttpContext.RequestAborted); + var posts = _blogPostRepository.ToList(); //TODO: async..? return View(posts); } } diff --git a/src/AbpDesk/AbpDesk.Web.Mvc/Controllers/IdentityServerTestController.cs b/src/AbpDesk/AbpDesk.Web.Mvc/Controllers/IdentityServerTestController.cs index 365efc29ee..fdd402d4a4 100644 --- a/src/AbpDesk/AbpDesk.Web.Mvc/Controllers/IdentityServerTestController.cs +++ b/src/AbpDesk/AbpDesk.Web.Mvc/Controllers/IdentityServerTestController.cs @@ -38,7 +38,7 @@ namespace AbpDesk.Web.Mvc.Controllers [Route("create")] public async Task CreateClient(string clientId) { - var apiResource = (await _apiResourceRepository.GetListAsync()).FirstOrDefault(ar => ar.Name == "api1"); + var apiResource = await _apiResourceRepository.FindByNameAsync("api1"); if (apiResource == null) { diff --git a/src/AbpDesk/Web_PlugIns/AbpDesk.MongoBlog.dll b/src/AbpDesk/Web_PlugIns/AbpDesk.MongoBlog.dll index 879b5f90bd..9fbb3846a6 100644 Binary files a/src/AbpDesk/Web_PlugIns/AbpDesk.MongoBlog.dll and b/src/AbpDesk/Web_PlugIns/AbpDesk.MongoBlog.dll differ diff --git a/src/Volo.Abp.Ddd/Microsoft/Extensions/DependencyInjection/ServiceCollectionRepositoryExtensions.cs b/src/Volo.Abp.Ddd/Microsoft/Extensions/DependencyInjection/ServiceCollectionRepositoryExtensions.cs index 12b0a3dbba..7ef9838f18 100644 --- a/src/Volo.Abp.Ddd/Microsoft/Extensions/DependencyInjection/ServiceCollectionRepositoryExtensions.cs +++ b/src/Volo.Abp.Ddd/Microsoft/Extensions/DependencyInjection/ServiceCollectionRepositoryExtensions.cs @@ -4,66 +4,49 @@ using Microsoft.Extensions.DependencyInjection.Extensions; using Volo.Abp; using Volo.Abp.Domain.Entities; using Volo.Abp.Domain.Repositories; -using Volo.Abp.Reflection; namespace Microsoft.Extensions.DependencyInjection { public static class ServiceCollectionRepositoryExtensions { - public static void AddDefaultRepository(this IServiceCollection services, Type entityType, Type repositoryImplementationType) + public static IServiceCollection AddDefaultRepository(this IServiceCollection services, Type entityType, Type repositoryImplementationType) { - AddDefaultRepositoryForGenericPrimaryKey(services, entityType, repositoryImplementationType); - - if (BothSupportsDefaultPrimaryKey(entityType, repositoryImplementationType)) - { - AddDefaultRepositoryForDefaultPrimaryKey(services, entityType, repositoryImplementationType); - } - } - - private static void AddDefaultRepositoryForGenericPrimaryKey(IServiceCollection services, Type entityType, Type repositoryImplementationType) - { - var primaryKeyType = EntityHelper.GetPrimaryKeyType(entityType); - - //IRepository - var repositoryInterface = typeof(IRepository<,>).MakeGenericType(entityType, primaryKeyType); - if (!repositoryInterface.GetTypeInfo().IsAssignableFrom(repositoryImplementationType)) + //IRepository + var repositoryInterfaceWithoutPk = typeof(IBasicRepository<>).MakeGenericType(entityType); + if (!repositoryInterfaceWithoutPk.IsAssignableFrom(repositoryImplementationType)) { - throw new AbpException($"Given repositoryImplementationType ({repositoryImplementationType}) must implement {repositoryInterface}"); + throw new AbpException($"Given repositoryImplementationType ({repositoryImplementationType}) must implement {repositoryInterfaceWithoutPk}"); } - services.TryAddTransient(repositoryInterface, repositoryImplementationType); - - //IQueryableRepository - var queryableRepositoryInterface = typeof(IQueryableRepository<,>).MakeGenericType(entityType, primaryKeyType); - if (queryableRepositoryInterface.GetTypeInfo().IsAssignableFrom(repositoryImplementationType)) - { - services.TryAddTransient(queryableRepositoryInterface, repositoryImplementationType); - } - } + services.TryAddTransient(repositoryInterfaceWithoutPk, repositoryImplementationType); - private static void AddDefaultRepositoryForDefaultPrimaryKey(IServiceCollection services, Type entityType, Type repositoryImplementationType) - { - //IRepository - var repositoryInterfaceWithDefaultPrimaryKey = typeof(IRepository<>).MakeGenericType(entityType); - if (!repositoryInterfaceWithDefaultPrimaryKey.GetTypeInfo().IsAssignableFrom(repositoryImplementationType)) + //IQueryableRepository + var queryableRepositoryInterfaceWithPk = typeof(IRepository<>).MakeGenericType(entityType); + if (repositoryInterfaceWithoutPk.IsAssignableFrom(repositoryImplementationType)) { - throw new AbpException($"Given repositoryImplementationType ({repositoryImplementationType}) must implement {repositoryInterfaceWithDefaultPrimaryKey}"); + services.TryAddTransient(queryableRepositoryInterfaceWithPk, repositoryImplementationType); } - services.TryAddTransient(repositoryInterfaceWithDefaultPrimaryKey, repositoryImplementationType); + var primaryKeyType = EntityHelper.FindPrimaryKeyType(entityType); - //IQueryableRepository - var queryableRepositoryInterfaceWithDefaultPrimaryKey = typeof(IQueryableRepository<>).MakeGenericType(entityType); - if (queryableRepositoryInterfaceWithDefaultPrimaryKey.GetTypeInfo().IsAssignableFrom(repositoryImplementationType)) + if (primaryKeyType != null) { - services.TryAddTransient(queryableRepositoryInterfaceWithDefaultPrimaryKey, repositoryImplementationType); + //IRepository + var repositoryInterface = typeof(IBasicRepository<,>).MakeGenericType(entityType, primaryKeyType); + if (repositoryInterface.GetTypeInfo().IsAssignableFrom(repositoryImplementationType)) + { + services.TryAddTransient(repositoryInterface, repositoryImplementationType); + } + + //IQueryableRepository + var queryableRepositoryInterface = typeof(IRepository<,>).MakeGenericType(entityType, primaryKeyType); + if (queryableRepositoryInterface.GetTypeInfo().IsAssignableFrom(repositoryImplementationType)) + { + services.TryAddTransient(queryableRepositoryInterface, repositoryImplementationType); + } } - } - private static bool BothSupportsDefaultPrimaryKey(Type entityType, Type repositoryImplementationType) - { - return typeof(IEntity).GetTypeInfo().IsAssignableFrom(entityType) && - ReflectionHelper.IsAssignableToGenericType(repositoryImplementationType, typeof(IRepository<>)); + return services; } } } \ No newline at end of file diff --git a/src/Volo.Abp.Ddd/Volo/Abp/Application/Dtos/EntityDto.cs b/src/Volo.Abp.Ddd/Volo/Abp/Application/Dtos/EntityDto.cs index 87f1457e86..76407cf8a5 100644 --- a/src/Volo.Abp.Ddd/Volo/Abp/Application/Dtos/EntityDto.cs +++ b/src/Volo.Abp.Ddd/Volo/Abp/Application/Dtos/EntityDto.cs @@ -1,41 +1,22 @@ -using System; - namespace Volo.Abp.Application.Dtos { - public class EntityDto : EntityDto, IEntityDto + public class EntityDto : IEntityDto //TODO: Consider to delete this class { - /// - /// Creates a new object. - /// - public EntityDto() - { - - } - - /// - /// Creates a new object. - /// - /// Id of the entity - public EntityDto(Guid id) - : base(id) + public override string ToString() { - + return $"[DTO: {GetType().Name}]"; } } - /// - /// Implements common properties for entity based DTOs. - /// - /// Type of the primary key - public class EntityDto : IEntityDto + public class EntityDto : EntityDto, IEntityDto { /// /// Id of the entity. /// - public TPrimaryKey Id { get; set; } + public TKey Id { get; set; } /// - /// Creates a new object. + /// Creates a new object. /// public EntityDto() { @@ -43,17 +24,17 @@ namespace Volo.Abp.Application.Dtos } /// - /// Creates a new object. + /// Creates a new object. /// /// Id of the entity - public EntityDto(TPrimaryKey id) + public EntityDto(TKey id) { Id = id; } public override string ToString() { - return $"[{GetType().Name}] Id = {Id}"; + return $"[DTO: {GetType().Name}] Id = {Id}"; } } } \ No newline at end of file diff --git a/src/Volo.Abp.Ddd/Volo/Abp/Application/Dtos/IEntityDto.cs b/src/Volo.Abp.Ddd/Volo/Abp/Application/Dtos/IEntityDto.cs index 390e2fb743..1f774e50d1 100644 --- a/src/Volo.Abp.Ddd/Volo/Abp/Application/Dtos/IEntityDto.cs +++ b/src/Volo.Abp.Ddd/Volo/Abp/Application/Dtos/IEntityDto.cs @@ -1,24 +1,12 @@ -using System; - -namespace Volo.Abp.Application.Dtos +namespace Volo.Abp.Application.Dtos { - /// - /// A shortcut of for default primary key type (). - /// - public interface IEntityDto : IEntityDto + public interface IEntityDto { } - /// - /// Defines common properties for entity based DTOs. - /// - /// - public interface IEntityDto + public interface IEntityDto : IEntityDto { - /// - /// Id of the entity. - /// - TPrimaryKey Id { get; set; } + TKey Id { get; set; } } } \ No newline at end of file diff --git a/src/Volo.Abp.Ddd/Volo/Abp/Application/Services/AsyncCrudAppService.cs b/src/Volo.Abp.Ddd/Volo/Abp/Application/Services/AsyncCrudAppService.cs index 0ed329c655..108b73b1ba 100644 --- a/src/Volo.Abp.Ddd/Volo/Abp/Application/Services/AsyncCrudAppService.cs +++ b/src/Volo.Abp.Ddd/Volo/Abp/Application/Services/AsyncCrudAppService.cs @@ -1,5 +1,4 @@ -using System; -using System.Linq; +using System.Linq; using System.Threading.Tasks; using Volo.Abp.Application.Dtos; using Volo.Abp.Domain.Entities; @@ -8,71 +7,59 @@ using Volo.Abp.Linq; namespace Volo.Abp.Application.Services { - public abstract class AsyncCrudAppService - : AsyncCrudAppService - where TEntity : class, IEntity - where TEntityDto : IEntityDto + public abstract class AsyncCrudAppService + : AsyncCrudAppService + where TEntity : class, IEntity + where TEntityDto : IEntityDto { - protected AsyncCrudAppService(IQueryableRepository repository) + protected AsyncCrudAppService(IRepository repository) : base(repository) { } } - public abstract class AsyncCrudAppService - : AsyncCrudAppService - where TEntity : class, IEntity - where TEntityDto : IEntityDto + public abstract class AsyncCrudAppService + : AsyncCrudAppService + where TEntity : class, IEntity + where TEntityDto : IEntityDto { - protected AsyncCrudAppService(IQueryableRepository repository) + protected AsyncCrudAppService(IRepository repository) : base(repository) { } } - public abstract class AsyncCrudAppService - : AsyncCrudAppService - where TEntity : class, IEntity - where TEntityDto : IEntityDto - { - protected AsyncCrudAppService(IQueryableRepository repository) - : base(repository) - { - - } - } - - public abstract class AsyncCrudAppService - : AsyncCrudAppService + public abstract class AsyncCrudAppService + : AsyncCrudAppService where TGetAllInput : IPagedAndSortedResultRequest - where TEntity : class, IEntity - where TEntityDto : IEntityDto - where TCreateInput : IEntityDto + where TEntity : class, IEntity + where TEntityDto : IEntityDto + where TCreateInput : IEntityDto { - protected AsyncCrudAppService(IQueryableRepository repository) + protected AsyncCrudAppService(IRepository repository) : base(repository) { } } - public abstract class AsyncCrudAppService - : CrudAppServiceBase, - IAsyncCrudAppService - where TEntity : class, IEntity - where TEntityDto : IEntityDto + public abstract class AsyncCrudAppService + : CrudAppServiceBase, + IAsyncCrudAppService + where TEntity : class, IEntity + where TEntityDto : IEntityDto { public IAsyncQueryableExecuter AsyncQueryableExecuter { get; set; } - protected AsyncCrudAppService(IQueryableRepository repository) + protected AsyncCrudAppService(IRepository repository) :base(repository) { AsyncQueryableExecuter = DefaultAsyncQueryableExecuter.Instance; } - public virtual async Task GetAsync(TPrimaryKey id) + public virtual async Task GetAsync(TKey id) { CheckGetPermission(); @@ -111,7 +98,7 @@ namespace Volo.Abp.Application.Services return MapToEntityDto(entity); } - public virtual async Task UpdateAsync(TPrimaryKey id, TUpdateInput input) + public virtual async Task UpdateAsync(TKey id, TUpdateInput input) { CheckUpdatePermission(); @@ -125,14 +112,14 @@ namespace Volo.Abp.Application.Services return MapToEntityDto(entity); } - public virtual Task DeleteAsync(TPrimaryKey id) + public virtual Task DeleteAsync(TKey id) { CheckDeletePermission(); return Repository.DeleteAsync(id); } - protected virtual Task GetEntityByIdAsync(TPrimaryKey id) + protected virtual Task GetEntityByIdAsync(TKey id) { return Repository.GetAsync(id); } diff --git a/src/Volo.Abp.Ddd/Volo/Abp/Application/Services/CrudAppService.cs b/src/Volo.Abp.Ddd/Volo/Abp/Application/Services/CrudAppService.cs index 127d0acd62..68618a553e 100644 --- a/src/Volo.Abp.Ddd/Volo/Abp/Application/Services/CrudAppService.cs +++ b/src/Volo.Abp.Ddd/Volo/Abp/Application/Services/CrudAppService.cs @@ -1,73 +1,60 @@ -using System; -using System.Linq; +using System.Linq; using Volo.Abp.Application.Dtos; using Volo.Abp.Domain.Entities; using Volo.Abp.Domain.Repositories; namespace Volo.Abp.Application.Services { - public abstract class CrudAppService - : CrudAppService - where TEntity : class, IEntity - where TEntityDto : IEntityDto + public abstract class CrudAppService + : CrudAppService + where TEntity : class, IEntity + where TEntityDto : IEntityDto { - protected CrudAppService(IQueryableRepository repository) + protected CrudAppService(IRepository repository) : base(repository) { } } - public abstract class CrudAppService - : CrudAppService - where TEntity : class, IEntity - where TEntityDto : IEntityDto + public abstract class CrudAppService + : CrudAppService + where TEntity : class, IEntity + where TEntityDto : IEntityDto { - protected CrudAppService(IQueryableRepository repository) + protected CrudAppService(IRepository repository) : base(repository) { } } - public abstract class CrudAppService - : CrudAppService - where TEntity : class, IEntity - where TEntityDto : IEntityDto + public abstract class CrudAppService + : CrudAppService + where TEntity : class, IEntity + where TEntityDto : IEntityDto + where TCreateInput : IEntityDto { - protected CrudAppService(IQueryableRepository repository) + protected CrudAppService(IRepository repository) : base(repository) { } } - public abstract class CrudAppService - : CrudAppService - where TEntity : class, IEntity - where TEntityDto : IEntityDto - where TCreateInput : IEntityDto + public abstract class CrudAppService + : CrudAppServiceBase, + ICrudAppService + where TEntity : class, IEntity + where TEntityDto : IEntityDto { - protected CrudAppService(IQueryableRepository repository) - : base(repository) - { - - } - } - - public abstract class CrudAppService - : CrudAppServiceBase, - ICrudAppService - where TEntity : class, IEntity - where TEntityDto : IEntityDto - { - protected CrudAppService(IQueryableRepository repository) + protected CrudAppService(IRepository repository) : base(repository) { } - public virtual TEntityDto Get(TPrimaryKey id) + public virtual TEntityDto Get(TKey id) { CheckGetPermission(); @@ -106,7 +93,7 @@ namespace Volo.Abp.Application.Services return MapToEntityDto(entity); } - public virtual TEntityDto Update(TPrimaryKey id, TUpdateInput input) + public virtual TEntityDto Update(TKey id, TUpdateInput input) { CheckUpdatePermission(); @@ -118,14 +105,14 @@ namespace Volo.Abp.Application.Services return MapToEntityDto(entity); } - public virtual void Delete(TPrimaryKey id) + public virtual void Delete(TKey id) { CheckDeletePermission(); Repository.Delete(id); } - protected virtual TEntity GetEntityById(TPrimaryKey id) + protected virtual TEntity GetEntityById(TKey id) { return Repository.Get(id); } diff --git a/src/Volo.Abp.Ddd/Volo/Abp/Application/Services/CrudAppServiceBase.cs b/src/Volo.Abp.Ddd/Volo/Abp/Application/Services/CrudAppServiceBase.cs index 3cdff642f1..f3441775a0 100644 --- a/src/Volo.Abp.Ddd/Volo/Abp/Application/Services/CrudAppServiceBase.cs +++ b/src/Volo.Abp.Ddd/Volo/Abp/Application/Services/CrudAppServiceBase.cs @@ -12,11 +12,11 @@ namespace Volo.Abp.Application.Services /// This is a common base class for CrudAppService and AsyncCrudAppService classes. /// Inherit either from CrudAppService or AsyncCrudAppService, not from this class. /// - public abstract class CrudAppServiceBase : ApplicationService - where TEntity : class, IEntity - where TEntityDto : IEntityDto + public abstract class CrudAppServiceBase : ApplicationService + where TEntity : class, IEntity + where TEntityDto : IEntityDto { - protected IQueryableRepository Repository { get; } + protected IRepository Repository { get; } protected virtual string GetPermissionName { get; set; } @@ -28,7 +28,7 @@ namespace Volo.Abp.Application.Services protected virtual string DeletePermissionName { get; set; } - protected CrudAppServiceBase(IQueryableRepository repository) + protected CrudAppServiceBase(IRepository repository) { Repository = repository; } @@ -120,7 +120,7 @@ namespace Volo.Abp.Application.Services } /// - /// Sets Id value for the entity if is . + /// Sets Id value for the entity if is . /// It's used while creating a new entity. /// protected virtual void SetIdForGuids(TEntity entity) diff --git a/src/Volo.Abp.Ddd/Volo/Abp/Application/Services/IAsyncCrudAppService.cs b/src/Volo.Abp.Ddd/Volo/Abp/Application/Services/IAsyncCrudAppService.cs index a94d0ce554..4f97c49ae0 100644 --- a/src/Volo.Abp.Ddd/Volo/Abp/Application/Services/IAsyncCrudAppService.cs +++ b/src/Volo.Abp.Ddd/Volo/Abp/Application/Services/IAsyncCrudAppService.cs @@ -1,49 +1,41 @@ -using System; using System.Threading.Tasks; using Volo.Abp.Application.Dtos; namespace Volo.Abp.Application.Services { - public interface IAsyncCrudAppService - : IAsyncCrudAppService - where TEntityDto : IEntityDto + public interface IAsyncCrudAppService + : IAsyncCrudAppService + where TEntityDto : IEntityDto { } - public interface IAsyncCrudAppService - : IAsyncCrudAppService - where TEntityDto : IEntityDto + public interface IAsyncCrudAppService + : IAsyncCrudAppService + where TEntityDto : IEntityDto { } - public interface IAsyncCrudAppService - : IAsyncCrudAppService - where TEntityDto : IEntityDto + public interface IAsyncCrudAppService + : IAsyncCrudAppService + where TEntityDto : IEntityDto { } - public interface IAsyncCrudAppService - : IAsyncCrudAppService - where TEntityDto : IEntityDto - { - - } - - public interface IAsyncCrudAppService + public interface IAsyncCrudAppService : IApplicationService - where TEntityDto : IEntityDto + where TEntityDto : IEntityDto { - Task GetAsync(TPrimaryKey id); + Task GetAsync(TKey id); Task> GetListAsync(TGetListInput input); Task CreateAsync(TCreateInput input); - Task UpdateAsync(TPrimaryKey id, TUpdateInput input); + Task UpdateAsync(TKey id, TUpdateInput input); - Task DeleteAsync(TPrimaryKey id); + Task DeleteAsync(TKey id); } } diff --git a/src/Volo.Abp.Ddd/Volo/Abp/Application/Services/ICrudAppService.cs b/src/Volo.Abp.Ddd/Volo/Abp/Application/Services/ICrudAppService.cs index a67aa83210..9f06c63aea 100644 --- a/src/Volo.Abp.Ddd/Volo/Abp/Application/Services/ICrudAppService.cs +++ b/src/Volo.Abp.Ddd/Volo/Abp/Application/Services/ICrudAppService.cs @@ -1,48 +1,40 @@ -using System; using Volo.Abp.Application.Dtos; namespace Volo.Abp.Application.Services { - public interface ICrudAppService - : ICrudAppService - where TEntityDto : IEntityDto + public interface ICrudAppService + : ICrudAppService + where TEntityDto : IEntityDto { } - public interface ICrudAppService - : ICrudAppService - where TEntityDto : IEntityDto + public interface ICrudAppService + : ICrudAppService + where TEntityDto : IEntityDto { } - public interface ICrudAppService - : ICrudAppService - where TEntityDto : IEntityDto + public interface ICrudAppService + : ICrudAppService + where TEntityDto : IEntityDto { } - public interface ICrudAppService - : ICrudAppService - where TEntityDto : IEntityDto - { - - } - - public interface ICrudAppService + public interface ICrudAppService : IApplicationService - where TEntityDto : IEntityDto + where TEntityDto : IEntityDto { - TEntityDto Get(TPrimaryKey id); + TEntityDto Get(TKey id); PagedResultDto GetAll(TGetListInput input); TEntityDto Create(TCreateInput input); - TEntityDto Update(TPrimaryKey id, TUpdateInput input); + TEntityDto Update(TKey id, TUpdateInput input); - void Delete(TPrimaryKey id); + void Delete(TKey id); } } diff --git a/src/Volo.Abp.Ddd/Volo/Abp/DependencyInjection/CommonDbContextRegistrationOptions.cs b/src/Volo.Abp.Ddd/Volo/Abp/DependencyInjection/CommonDbContextRegistrationOptions.cs index 99f087c54d..3ad73cca1c 100644 --- a/src/Volo.Abp.Ddd/Volo/Abp/DependencyInjection/CommonDbContextRegistrationOptions.cs +++ b/src/Volo.Abp.Ddd/Volo/Abp/DependencyInjection/CommonDbContextRegistrationOptions.cs @@ -1,6 +1,5 @@ using System; using System.Collections.Generic; -using JetBrains.Annotations; using Volo.Abp.Domain.Entities; using Volo.Abp.Domain.Repositories; using Volo.Abp.Reflection; @@ -20,7 +19,7 @@ namespace Volo.Abp.DependencyInjection public Type DefaultRepositoryImplementationType { get; private set; } - public Type DefaultRepositoryImplementationTypeWithDefaultPrimaryKey { get; private set; } + public Type DefaultRepositoryImplementationTypeWithouTKey { get; private set; } public bool RegisterDefaultRepositories { get; private set; } @@ -28,7 +27,7 @@ namespace Volo.Abp.DependencyInjection public Dictionary CustomRepositories { get; } - public bool SpecifiedDefaultRepositoryTypes => DefaultRepositoryImplementationType != null && DefaultRepositoryImplementationTypeWithDefaultPrimaryKey != null; + public bool SpecifiedDefaultRepositoryTypes => DefaultRepositoryImplementationType != null && DefaultRepositoryImplementationTypeWithouTKey != null; protected CommonDbContextRegistrationOptions(Type originalDbContextType) { @@ -80,34 +79,37 @@ namespace Volo.Abp.DependencyInjection return this; } - public ICommonDbContextRegistrationOptionsBuilder AddCustomRepository() + public ICommonDbContextRegistrationOptionsBuilder AddRepository() { - WithCustomRepository(typeof(TEntity), typeof(TRepository)); + AddCustomRepository(typeof(TEntity), typeof(TRepository)); return this; } - public ICommonDbContextRegistrationOptionsBuilder SetDefaultRepositoryClasses([NotNull] Type repositoryImplementationType, [NotNull] Type repositoryImplementationTypeWithDefaultPrimaryKey) + public ICommonDbContextRegistrationOptionsBuilder SetDefaultRepositoryClasses( + Type repositoryImplementationType, + Type repositoryImplementationTypeWithouTKey + ) { Check.NotNull(repositoryImplementationType, nameof(repositoryImplementationType)); - Check.NotNull(repositoryImplementationTypeWithDefaultPrimaryKey, nameof(repositoryImplementationTypeWithDefaultPrimaryKey)); + Check.NotNull(repositoryImplementationTypeWithouTKey, nameof(repositoryImplementationTypeWithouTKey)); DefaultRepositoryImplementationType = repositoryImplementationType; - DefaultRepositoryImplementationTypeWithDefaultPrimaryKey = repositoryImplementationTypeWithDefaultPrimaryKey; + DefaultRepositoryImplementationTypeWithouTKey = repositoryImplementationTypeWithouTKey; return this; } - private void WithCustomRepository(Type entityType, Type repositoryType) + private void AddCustomRepository(Type entityType, Type repositoryType) { - if (!ReflectionHelper.IsAssignableToGenericType(entityType, typeof(IEntity<>))) + if (!typeof(IEntity).IsAssignableFrom(entityType)) { throw new AbpException($"Given entityType is not an entity: {entityType.AssemblyQualifiedName}. It must implement {typeof(IEntity<>).AssemblyQualifiedName}."); } - if (!ReflectionHelper.IsAssignableToGenericType(repositoryType, typeof(IRepository<,>))) + if (!ReflectionHelper.IsAssignableToGenericType(repositoryType, typeof(IBasicRepository<>))) { - throw new AbpException($"Given repositoryType is not a repository: {entityType.AssemblyQualifiedName}. It must implement {typeof(IRepository<,>).AssemblyQualifiedName}."); + throw new AbpException($"Given repositoryType is not a repository: {entityType.AssemblyQualifiedName}. It must implement {typeof(IBasicRepository<>).AssemblyQualifiedName}."); } CustomRepositories[entityType] = repositoryType; @@ -125,7 +127,7 @@ namespace Volo.Abp.DependencyInjection return false; } - if (!IncludeAllEntitiesForDefaultRepositories && !ReflectionHelper.IsAssignableToGenericType(entityType, typeof(IAggregateRoot<>))) + if (!IncludeAllEntitiesForDefaultRepositories && !typeof(IAggregateRoot).IsAssignableFrom(entityType)) { return false; } diff --git a/src/Volo.Abp.Ddd/Volo/Abp/DependencyInjection/ICommonDbContextRegistrationOptionsBuilder.cs b/src/Volo.Abp.Ddd/Volo/Abp/DependencyInjection/ICommonDbContextRegistrationOptionsBuilder.cs index f15509dfbe..837f7bc110 100644 --- a/src/Volo.Abp.Ddd/Volo/Abp/DependencyInjection/ICommonDbContextRegistrationOptionsBuilder.cs +++ b/src/Volo.Abp.Ddd/Volo/Abp/DependencyInjection/ICommonDbContextRegistrationOptionsBuilder.cs @@ -1,4 +1,5 @@ using System; +using JetBrains.Annotations; namespace Volo.Abp.DependencyInjection { @@ -41,15 +42,15 @@ namespace Volo.Abp.DependencyInjection /// /// Entity type /// Repository type - ICommonDbContextRegistrationOptionsBuilder AddCustomRepository(); //TODO: Rename to AddRepository! + ICommonDbContextRegistrationOptionsBuilder AddRepository(); /// /// Uses given class(es) for default repositories. /// /// Repository implementation type - /// Repository implementation type for default primary key type () + /// Repository implementation type (without primary key) /// - ICommonDbContextRegistrationOptionsBuilder SetDefaultRepositoryClasses(Type repositoryImplementationType, Type repositoryImplementationTypeWithDefaultPrimaryKey); + ICommonDbContextRegistrationOptionsBuilder SetDefaultRepositoryClasses([NotNull] Type repositoryImplementationType, [NotNull] Type repositoryImplementationTypeWithouTKey); /// /// Replaces given DbContext type with this DbContext type. diff --git a/src/Volo.Abp.Ddd/Volo/Abp/Domain/Entities/AggregateRoot.cs b/src/Volo.Abp.Ddd/Volo/Abp/Domain/Entities/AggregateRoot.cs index 3c8d2771f5..a2b233406f 100644 --- a/src/Volo.Abp.Ddd/Volo/Abp/Domain/Entities/AggregateRoot.cs +++ b/src/Volo.Abp.Ddd/Volo/Abp/Domain/Entities/AggregateRoot.cs @@ -1,13 +1,14 @@ -using System; - -namespace Volo.Abp.Domain.Entities +namespace Volo.Abp.Domain.Entities { - public abstract class AggregateRoot : AggregateRoot, IAggregateRoot + + /// + public abstract class AggregateRoot : IAggregateRoot { } - public abstract class AggregateRoot : Entity, IAggregateRoot + /// + public abstract class AggregateRoot : Entity, IAggregateRoot { } diff --git a/src/Volo.Abp.Ddd/Volo/Abp/Domain/Entities/Entity.cs b/src/Volo.Abp.Ddd/Volo/Abp/Domain/Entities/Entity.cs index 33e7220166..007442f781 100644 --- a/src/Volo.Abp.Ddd/Volo/Abp/Domain/Entities/Entity.cs +++ b/src/Volo.Abp.Ddd/Volo/Abp/Domain/Entities/Entity.cs @@ -1,37 +1,27 @@ -using System; -using System.Reflection; +using System.Reflection; namespace Volo.Abp.Domain.Entities { - /// - /// A shortcut of for default primary key type (). - /// - public abstract class Entity : Entity, IEntity - { - - } - /// - /// - /// Basic implementation of IEntity interface. - /// An entity can inherit this class of directly implement to IEntity interface. - /// - /// Type of the primary key of the entity - public abstract class Entity : IEntity + public abstract class Entity : IEntity { /// - public virtual TPrimaryKey Id { get; set; } - - /// - public virtual bool IsTransient() + public override string ToString() { - return EntityHelper.IsTransient(this); + return $"[ENTITY: {GetType().Name}]"; } + } + + /// + public abstract class Entity : Entity, IEntity + { + /// + public virtual TKey Id { get; set; } /// public override bool Equals(object obj) { - if (obj == null || !(obj is Entity)) + if (obj == null || !(obj is Entity)) { return false; } @@ -43,8 +33,8 @@ namespace Volo.Abp.Domain.Entities } //Transient objects are not considered as equal - var other = (Entity)obj; - if (IsTransient() && other.IsTransient()) + var other = (Entity)obj; + if (EntityHelper.IsTransient(this) && EntityHelper.IsTransient(other)) { return false; } @@ -63,10 +53,15 @@ namespace Volo.Abp.Domain.Entities /// public override int GetHashCode() { + if (Id == null) + { + return 0; + } + return Id.GetHashCode(); } - public static bool operator ==(Entity left, Entity right) + public static bool operator ==(Entity left, Entity right) { if (Equals(left, null)) { @@ -76,7 +71,7 @@ namespace Volo.Abp.Domain.Entities return left.Equals(right); } - public static bool operator !=(Entity left, Entity right) + public static bool operator !=(Entity left, Entity right) { return !(left == right); } @@ -84,7 +79,7 @@ namespace Volo.Abp.Domain.Entities /// public override string ToString() { - return $"[{GetType().Name} {Id}]"; + return $"[ENTITY: {GetType().Name}] Id = {Id}"; } } } diff --git a/src/Volo.Abp.Ddd/Volo/Abp/Domain/Entities/EntityHelper.cs b/src/Volo.Abp.Ddd/Volo/Abp/Domain/Entities/EntityHelper.cs index 304d664850..18f6f2a8e9 100644 --- a/src/Volo.Abp.Ddd/Volo/Abp/Domain/Entities/EntityHelper.cs +++ b/src/Volo.Abp.Ddd/Volo/Abp/Domain/Entities/EntityHelper.cs @@ -1,8 +1,8 @@ using System; using System.Collections.Generic; +using System.Linq.Expressions; using System.Reflection; using JetBrains.Annotations; -using Volo.Abp.Reflection; namespace Volo.Abp.Domain.Entities { @@ -13,32 +13,23 @@ namespace Volo.Abp.Domain.Entities { public static bool IsEntity([NotNull] Type type) { - return ReflectionHelper.IsAssignableToGenericType(type, typeof (IEntity<>)); + return typeof(IEntity).IsAssignableFrom(type); } - /// - /// Default implementation of . - /// - /// This method is not used normally if given entity is derived from . - /// Just directly call . - /// - /// This method is exists to help developers who want to directly implement - /// but want to use default IsTransient implementation as a shortcut. - /// - public static bool IsTransient(IEntity entity) + public static bool IsTransient(IEntity entity) // TODO: Completely remove IsTransient { - if (EqualityComparer.Default.Equals(entity.Id, default)) + if (EqualityComparer.Default.Equals(entity.Id, default)) { return true; } //Workaround for EF Core since it sets int/long to min value when attaching to dbcontext - if (typeof(TPrimaryKey) == typeof(int)) + if (typeof(TKey) == typeof(int)) { return Convert.ToInt32(entity.Id) <= 0; } - if (typeof(TPrimaryKey) == typeof(long)) + if (typeof(TKey) == typeof(long)) { return Convert.ToInt64(entity.Id) <= 0; } @@ -46,25 +37,50 @@ namespace Volo.Abp.Domain.Entities return false; } - public static Type GetPrimaryKeyType() + /// + /// Tries to find the primary key type of the given entity type. + /// May return null if given type does not implement + /// + [CanBeNull] + public static Type FindPrimaryKeyType() + where TEntity : IEntity { - return GetPrimaryKeyType(typeof (TEntity)); + return FindPrimaryKeyType(typeof(TEntity)); } /// - /// Gets primary key type of given entity type + /// Tries to find the primary key type of the given entity type. + /// May return null if given type does not implement /// - public static Type GetPrimaryKeyType([NotNull] Type entityType) + [CanBeNull] + public static Type FindPrimaryKeyType([NotNull] Type entityType) { + if (!typeof(IEntity).IsAssignableFrom(entityType)) + { + throw new AbpException($"Given {nameof(entityType)} is not an entity. It should implement {typeof(IEntity).AssemblyQualifiedName}!"); + } + foreach (var interfaceType in entityType.GetTypeInfo().GetInterfaces()) { - if (interfaceType.GetTypeInfo().IsGenericType && interfaceType.GetGenericTypeDefinition() == typeof (IEntity<>)) + if (interfaceType.GetTypeInfo().IsGenericType && interfaceType.GetGenericTypeDefinition() == typeof(IEntity<>)) { return interfaceType.GenericTypeArguments[0]; } } - throw new AbpException("Can not find primary key type of given entity type: " + entityType + ". Be sure that this entity type implements " + typeof(IEntity<>).AssemblyQualifiedName); + return null; + } + + public static Expression> CreateEqualityExpressionForId(TKey id) + where TEntity : IEntity + { + var lambdaParam = Expression.Parameter(typeof(TEntity)); + var lambdaBody = Expression.Equal( + Expression.PropertyOrField(lambdaParam, "Id"), + Expression.Constant(id, typeof(TKey)) + ); + + return Expression.Lambda>(lambdaBody, lambdaParam); } } } \ No newline at end of file diff --git a/src/Volo.Abp.Ddd/Volo/Abp/Domain/Entities/EntityNotFoundException.cs b/src/Volo.Abp.Ddd/Volo/Abp/Domain/Entities/EntityNotFoundException.cs index a33a9b8a41..510d0384c2 100644 --- a/src/Volo.Abp.Ddd/Volo/Abp/Domain/Entities/EntityNotFoundException.cs +++ b/src/Volo.Abp.Ddd/Volo/Abp/Domain/Entities/EntityNotFoundException.cs @@ -25,6 +25,15 @@ namespace Volo.Abp.Domain.Entities } + /// + /// Creates a new object. + /// + public EntityNotFoundException(Type entityType) + : this(entityType, null, null) + { + + } + /// /// Creates a new object. /// diff --git a/src/Volo.Abp.Ddd/Volo/Abp/Domain/Entities/IAggregateRoot.cs b/src/Volo.Abp.Ddd/Volo/Abp/Domain/Entities/IAggregateRoot.cs index 9ef287eb68..bdb436c51d 100644 --- a/src/Volo.Abp.Ddd/Volo/Abp/Domain/Entities/IAggregateRoot.cs +++ b/src/Volo.Abp.Ddd/Volo/Abp/Domain/Entities/IAggregateRoot.cs @@ -1,13 +1,19 @@ -using System; - -namespace Volo.Abp.Domain.Entities +namespace Volo.Abp.Domain.Entities { - public interface IAggregateRoot : IAggregateRoot, IEntity + /// + /// Defines an aggregate root. It's primary key may not be "Id" or it may have a composite primary key. + /// Use where possible for better integration to repositories and other structures in the framework. + /// + public interface IAggregateRoot : IEntity { } - public interface IAggregateRoot : IEntity + /// + /// Defines an aggregate root with a single primary key with "Id" property. + /// + /// Type of the primary key of the entity + public interface IAggregateRoot : IEntity, IAggregateRoot { } diff --git a/src/Volo.Abp.Ddd/Volo/Abp/Domain/Entities/IEntity.cs b/src/Volo.Abp.Ddd/Volo/Abp/Domain/Entities/IEntity.cs index 2d48ee20e7..2f19d591f6 100644 --- a/src/Volo.Abp.Ddd/Volo/Abp/Domain/Entities/IEntity.cs +++ b/src/Volo.Abp.Ddd/Volo/Abp/Domain/Entities/IEntity.cs @@ -1,30 +1,23 @@ -using System; - -namespace Volo.Abp.Domain.Entities +namespace Volo.Abp.Domain.Entities { /// - /// A shortcut of for default primary key type (). + /// Defines an entity. It's primary key may not be "Id" or it mah have a composite primary key. + /// Use where possible for better integration to repositories and other structures in the framework. /// - public interface IEntity : IEntity + public interface IEntity { } /// - /// Defines interface for base entity type. All entities in the system must implement this interface. + /// Defines an entity with a single primary key with "Id" property. /// - /// Type of the primary key of the entity - public interface IEntity + /// Type of the primary key of the entity + public interface IEntity : IEntity { /// /// Unique identifier for this entity. /// - TPrimaryKey Id { get; set; } - - /// - /// Checks if this entity is transient (not persisted to database and it has not an ). - /// - /// True, if this entity is transient - bool IsTransient(); + TKey Id { get; set; } //TODO: Consider to remove setter and make it protected in Entity class } } diff --git a/src/Volo.Abp.Ddd/Volo/Abp/Domain/Repositories/BasicRepositoryBase.cs b/src/Volo.Abp.Ddd/Volo/Abp/Domain/Repositories/BasicRepositoryBase.cs new file mode 100644 index 0000000000..5870aeef06 --- /dev/null +++ b/src/Volo.Abp.Ddd/Volo/Abp/Domain/Repositories/BasicRepositoryBase.cs @@ -0,0 +1,90 @@ +using System.Threading; +using System.Threading.Tasks; +using Volo.Abp.Domain.Entities; +using Volo.Abp.Threading; + +namespace Volo.Abp.Domain.Repositories +{ + public abstract class BasicRepositoryBase : IBasicRepository + where TEntity : class, IEntity + { + public ICancellationTokenProvider CancellationTokenProvider { get; set; } + + protected BasicRepositoryBase() + { + CancellationTokenProvider = NullCancellationTokenProvider.Instance; + } + + public abstract TEntity Insert(TEntity entity, bool autoSave = false); + + public virtual Task InsertAsync(TEntity entity, bool autoSave = false, CancellationToken cancellationToken = default) + { + return Task.FromResult(Insert(entity, autoSave)); + } + + public abstract TEntity Update(TEntity entity); + + public virtual Task UpdateAsync(TEntity entity, CancellationToken cancellationToken = default) + { + return Task.FromResult(Update(entity)); + } + + public abstract void Delete(TEntity entity); + + public virtual Task DeleteAsync(TEntity entity, CancellationToken cancellationToken = default) + { + Delete(entity); + return Task.CompletedTask; + } + + protected virtual CancellationToken GetCancellationToken(CancellationToken prefferedValue = default) + { + return CancellationTokenProvider.FallbackToProvider(prefferedValue); + } + } + + public abstract class BasicRepositoryBase : BasicRepositoryBase, IBasicRepository + where TEntity : class, IEntity + { + public virtual TEntity Get(TKey id) + { + var entity = Find(id); + + if (entity == null) + { + throw new EntityNotFoundException(typeof(TEntity), id); + } + + return entity; + } + + public virtual Task GetAsync(TKey id, CancellationToken cancellationToken = default) + { + return Task.FromResult(Get(id)); + } + + public abstract TEntity Find(TKey id); + + public virtual Task FindAsync(TKey id, CancellationToken cancellationToken = default) + { + return Task.FromResult(Find(id)); + } + + public virtual void Delete(TKey id) + { + var entity = Find(id); + if (entity == null) + { + return; + } + + Delete(entity); + } + + public virtual Task DeleteAsync(TKey id, CancellationToken cancellationToken = default) + { + Delete(id); + return Task.CompletedTask; + } + } +} diff --git a/src/Volo.Abp.Ddd/Volo/Abp/Domain/Repositories/IBasicRepository.cs b/src/Volo.Abp.Ddd/Volo/Abp/Domain/Repositories/IBasicRepository.cs new file mode 100644 index 0000000000..91984a1848 --- /dev/null +++ b/src/Volo.Abp.Ddd/Volo/Abp/Domain/Repositories/IBasicRepository.cs @@ -0,0 +1,114 @@ +using System.Threading; +using System.Threading.Tasks; +using JetBrains.Annotations; +using Volo.Abp.Domain.Entities; + +namespace Volo.Abp.Domain.Repositories +{ + public interface IBasicRepository : IRepository + where TEntity : class, IEntity + { + /// + /// Inserts a new entity. + /// + /// Inserted entity + /// + /// Set true to automatically save changes to database. + /// This can be used to set database generated Id of an entity for some ORMs (like Entity Framework). + /// + [NotNull] + TEntity Insert([NotNull] TEntity entity, bool autoSave = false); + + /// + /// Inserts a new entity. + /// + /// + /// Set true to automatically save changes to database. + /// This can be used to set database generated Id of an entity for some ORMs (like Entity Framework). + /// + /// A to observe while waiting for the task to complete. + /// Inserted entity + [NotNull] + Task InsertAsync([NotNull] TEntity entity, bool autoSave = false, CancellationToken cancellationToken = default); + + /// + /// Updates an existing entity. + /// + /// Entity + [NotNull] + TEntity Update([NotNull] TEntity entity); + + /// + /// Updates an existing entity. + /// + /// A to observe while waiting for the task to complete. + /// Entity + [NotNull] + Task UpdateAsync([NotNull] TEntity entity, CancellationToken cancellationToken = default); + + /// + /// Deletes an entity. + /// + /// Entity to be deleted + void Delete([NotNull] TEntity entity); //TODO: Return true if deleted + + /// + /// Deletes an entity. + /// + /// A to observe while waiting for the task to complete. + /// Entity to be deleted + Task DeleteAsync([NotNull] TEntity entity, CancellationToken cancellationToken = default); //TODO: Return true if deleted + } + + public interface IBasicRepository : IBasicRepository + where TEntity : class, IEntity + { + /// + /// Gets an entity with given primary key. + /// Throws if can not find an entity with given id. + /// + /// Primary key of the entity to get + /// Entity + [NotNull] + TEntity Get(TKey id); + + /// + /// Gets an entity with given primary key. + /// Throws if can not find an entity with given id. + /// + /// Primary key of the entity to get + /// A to observe while waiting for the task to complete. + /// Entity + [NotNull] + Task GetAsync(TKey id, CancellationToken cancellationToken = default); + + /// + /// Gets an entity with given primary key or null if not found. + /// + /// Primary key of the entity to get + /// Entity or null + [CanBeNull] + TEntity Find(TKey id); + + /// + /// Gets an entity with given primary key or null if not found. + /// + /// Primary key of the entity to get + /// A to observe while waiting for the task to complete. + /// Entity or null + Task FindAsync(TKey id, CancellationToken cancellationToken = default); + + /// + /// Deletes an entity by primary key. + /// + /// Primary key of the entity + void Delete(TKey id); //TODO: Return true if deleted + + /// + /// Deletes an entity by primary key. + /// + /// A to observe while waiting for the task to complete. + /// Primary key of the entity + Task DeleteAsync(TKey id, CancellationToken cancellationToken = default); //TODO: Return true if deleted + } +} diff --git a/src/Volo.Abp.Ddd/Volo/Abp/Domain/Repositories/IQueryableRepository.cs b/src/Volo.Abp.Ddd/Volo/Abp/Domain/Repositories/IQueryableRepository.cs deleted file mode 100644 index 53e65ce336..0000000000 --- a/src/Volo.Abp.Ddd/Volo/Abp/Domain/Repositories/IQueryableRepository.cs +++ /dev/null @@ -1,39 +0,0 @@ -using System; -using System.Linq; -using System.Linq.Expressions; -using System.Threading; -using System.Threading.Tasks; -using JetBrains.Annotations; -using Volo.Abp.Domain.Entities; - -namespace Volo.Abp.Domain.Repositories -{ - public interface IQueryableRepository : IQueryableRepository, IRepository - where TEntity : class, IEntity - { - - } - - public interface IQueryableRepository : IRepository, IQueryable - where TEntity : class, IEntity - { - /// - /// Deletes many entities by function. - /// Notice that: All entities fits to given predicate are retrieved and deleted. - /// This may cause major performance problems if there are too many entities with - /// given predicate. - /// - /// A condition to filter entities - void Delete([NotNull] Expression> predicate); - - /// - /// Deletes many entities by function. - /// Notice that: All entities fits to given predicate are retrieved and deleted. - /// This may cause major performance problems if there are too many entities with - /// given predicate. - /// - /// A to observe while waiting for the task to complete. - /// A condition to filter entities - Task DeleteAsync([NotNull] Expression> predicate, CancellationToken cancellationToken = default); - } -} \ No newline at end of file diff --git a/src/Volo.Abp.Ddd/Volo/Abp/Domain/Repositories/IRepository.cs b/src/Volo.Abp.Ddd/Volo/Abp/Domain/Repositories/IRepository.cs index 2af29b9cbc..e927334b26 100644 --- a/src/Volo.Abp.Ddd/Volo/Abp/Domain/Repositories/IRepository.cs +++ b/src/Volo.Abp.Ddd/Volo/Abp/Domain/Repositories/IRepository.cs @@ -1,5 +1,6 @@ using System; -using System.Collections.Generic; +using System.Linq; +using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; using JetBrains.Annotations; @@ -8,143 +9,39 @@ using Volo.Abp.Domain.Entities; namespace Volo.Abp.Domain.Repositories { + /// + /// Just to mark a class as repository. + /// public interface IRepository : ITransientDependency { } - public interface IRepository : IRepository - where TEntity : class, IEntity + public interface IRepository : IBasicRepository, IQueryable + where TEntity : class, IEntity { - - } - - public interface IRepository : IRepository - where TEntity : class, IEntity - { - /// - /// Get list of all entities without any filtering. - /// - /// List of entities - List GetList(); - - /// - /// Get list of all entities without any filtering. - /// - /// A to observe while waiting for the task to complete. - /// List of entities - Task> GetListAsync(CancellationToken cancellationToken = default); - /// - /// Gets an entity with given primary key. - /// Throws if can not find an entity with given id. + /// Deletes many entities by function. + /// Notice that: All entities fits to given predicate are retrieved and deleted. + /// This may cause major performance problems if there are too many entities with + /// given predicate. /// - /// Primary key of the entity to get - /// Entity - [NotNull] - TEntity Get(TPrimaryKey id); + /// A condition to filter entities + void Delete([NotNull] Expression> predicate); /// - /// Gets an entity with given primary key. - /// Throws if can not find an entity with given id. + /// Deletes many entities by function. + /// Notice that: All entities fits to given predicate are retrieved and deleted. + /// This may cause major performance problems if there are too many entities with + /// given predicate. /// - /// Primary key of the entity to get /// A to observe while waiting for the task to complete. - /// Entity - [NotNull] - Task GetAsync(TPrimaryKey id, CancellationToken cancellationToken = default); - - /// - /// Gets an entity with given primary key or null if not found. - /// - /// Primary key of the entity to get - /// Entity or null - [CanBeNull] - TEntity Find(TPrimaryKey id); - - /// - /// Gets an entity with given primary key or null if not found. - /// - /// Primary key of the entity to get - /// A to observe while waiting for the task to complete. - /// Entity or null - Task FindAsync(TPrimaryKey id, CancellationToken cancellationToken = default); - - /// - /// Inserts a new entity. - /// - /// Inserted entity - /// - /// Set true to automatically save changes to database. - /// This can be used to set database generated Id of an entity for some ORMs (like Entity Framework). - /// - [NotNull] - TEntity Insert([NotNull] TEntity entity, bool autoSave = false); - - /// - /// Inserts a new entity. - /// - /// - /// Set true to automatically save changes to database. - /// This can be used to set database generated Id of an entity for some ORMs (like Entity Framework). - /// - /// A to observe while waiting for the task to complete. - /// Inserted entity - [NotNull] - Task InsertAsync([NotNull] TEntity entity, bool autoSave = false, CancellationToken cancellationToken = default); - - /// - /// Updates an existing entity. - /// - /// Entity - [NotNull] - TEntity Update([NotNull] TEntity entity); - - /// - /// Updates an existing entity. - /// - /// A to observe while waiting for the task to complete. - /// Entity - [NotNull] - Task UpdateAsync([NotNull] TEntity entity, CancellationToken cancellationToken = default); - - /// - /// Deletes an entity. - /// - /// Entity to be deleted - void Delete([NotNull] TEntity entity); //TODO: Return true if deleted - - /// - /// Deletes an entity. - /// - /// A to observe while waiting for the task to complete. - /// Entity to be deleted - Task DeleteAsync([NotNull] TEntity entity, CancellationToken cancellationToken = default); //TODO: Return true if deleted - - /// - /// Deletes an entity by primary key. - /// - /// Primary key of the entity - void Delete(TPrimaryKey id); //TODO: Return true if deleted - - /// - /// Deletes an entity by primary key. - /// - /// A to observe while waiting for the task to complete. - /// Primary key of the entity - Task DeleteAsync(TPrimaryKey id, CancellationToken cancellationToken = default); //TODO: Return true if deleted - - /// - /// Get list of all entities without any filtering. - /// - /// List of entities - long GetCount(); + /// A condition to filter entities + Task DeleteAsync([NotNull] Expression> predicate, CancellationToken cancellationToken = default); + } - /// - /// Get list of all entities without any filtering. - /// - /// A to observe while waiting for the task to complete. - /// List of entities - Task GetCountAsync(CancellationToken cancellationToken = default); + public interface IRepository : IRepository, IBasicRepository + where TEntity : class, IEntity + { } -} +} \ No newline at end of file diff --git a/src/Volo.Abp.Ddd/Volo/Abp/Domain/Repositories/ISupportsExplicitLoading.cs b/src/Volo.Abp.Ddd/Volo/Abp/Domain/Repositories/ISupportsExplicitLoading.cs index 9b4a98863c..79eb68daf6 100644 --- a/src/Volo.Abp.Ddd/Volo/Abp/Domain/Repositories/ISupportsExplicitLoading.cs +++ b/src/Volo.Abp.Ddd/Volo/Abp/Domain/Repositories/ISupportsExplicitLoading.cs @@ -7,8 +7,8 @@ using Volo.Abp.Domain.Entities; namespace Volo.Abp.Domain.Repositories { - public interface ISupportsExplicitLoading - where TEntity : class, IEntity + public interface ISupportsExplicitLoading + where TEntity : class, IEntity { Task EnsureCollectionLoadedAsync( TEntity entity, diff --git a/src/Volo.Abp.Ddd/Volo/Abp/Domain/Repositories/QueryableRepositoryBase.cs b/src/Volo.Abp.Ddd/Volo/Abp/Domain/Repositories/QueryableRepositoryBase.cs deleted file mode 100644 index d75d4b8f13..0000000000 --- a/src/Volo.Abp.Ddd/Volo/Abp/Domain/Repositories/QueryableRepositoryBase.cs +++ /dev/null @@ -1,90 +0,0 @@ -using System; -using System.Collections; -using System.Collections.Generic; -using System.Linq; -using System.Linq.Expressions; -using System.Threading; -using System.Threading.Tasks; -using Volo.Abp.Data; -using Volo.Abp.Domain.Entities; -using Volo.Abp.MultiTenancy; - -namespace Volo.Abp.Domain.Repositories -{ - public abstract class QueryableRepositoryBase : QueryableRepositoryBase, IQueryableRepository - where TEntity : class, IEntity - { - - } - - public abstract class QueryableRepositoryBase : RepositoryBase, IQueryableRepository - where TEntity : class, IEntity - { - public virtual Type ElementType => GetQueryable().ElementType; - - public virtual Expression Expression => GetQueryable().Expression; - - public virtual IQueryProvider Provider => GetQueryable().Provider; - - public IDataFilter DataFilter { get; set; } - - public ICurrentTenant CurrentTenant { get; set; } - - IEnumerator IEnumerable.GetEnumerator() - { - return GetEnumerator(); - } - - public IEnumerator GetEnumerator() - { - return GetQueryable().GetEnumerator(); - } - - protected abstract IQueryable GetQueryable(); - - public override List GetList() - { - return GetQueryable().ToList(); - } - - public override TEntity Find(TPrimaryKey id) - { - return GetQueryable().FirstOrDefault(CreateEqualityExpressionForId(id)); - } - - public virtual void Delete(Expression> predicate) - { - foreach (var entity in GetQueryable().Where(predicate).ToList()) - { - Delete(entity); - } - } - - public virtual Task DeleteAsync(Expression> predicate, CancellationToken cancellationToken = default) - { - Delete(predicate); - return Task.CompletedTask; - } - - public override long GetCount() - { - return GetQueryable().LongCount(); - } - - protected virtual IQueryable ApplyDataFilters(IQueryable query) - { - if (typeof(ISoftDelete).IsAssignableFrom(typeof(TEntity))) - { - query = query.WhereIf(DataFilter.IsEnabled(), e => ((ISoftDelete)e).IsDeleted == false); - } - - if (typeof(IMultiTenant).IsAssignableFrom(typeof(TEntity))) - { - var tenantId = CurrentTenant.Id; - query = query.WhereIf(DataFilter.IsEnabled(), e => ((IMultiTenant)e).TenantId == tenantId); - } - - return query; - } - } -} \ No newline at end of file diff --git a/src/Volo.Abp.Ddd/Volo/Abp/Domain/Repositories/RepositoryBase.cs b/src/Volo.Abp.Ddd/Volo/Abp/Domain/Repositories/RepositoryBase.cs index 062d130ad0..b716142436 100644 --- a/src/Volo.Abp.Ddd/Volo/Abp/Domain/Repositories/RepositoryBase.cs +++ b/src/Volo.Abp.Ddd/Volo/Abp/Domain/Repositories/RepositoryBase.cs @@ -1,83 +1,104 @@ using System; +using System.Collections; using System.Collections.Generic; +using System.Linq; using System.Linq.Expressions; using System.Threading; using System.Threading.Tasks; +using Volo.Abp.Data; using Volo.Abp.Domain.Entities; -using Volo.Abp.Threading; +using Volo.Abp.MultiTenancy; namespace Volo.Abp.Domain.Repositories { - public abstract class RepositoryBase : RepositoryBase, IRepository - where TEntity : class, IEntity + public abstract class RepositoryBase : BasicRepositoryBase, IRepository + where TEntity : class, IEntity { + public IDataFilter DataFilter { get; set; } - } + public ICurrentTenant CurrentTenant { get; set; } - public abstract class RepositoryBase : IRepository - where TEntity : class, IEntity - { - public ICancellationTokenProvider CancellationTokenProvider { get; set; } + public virtual Type ElementType => GetQueryable().ElementType; + + public virtual Expression Expression => GetQueryable().Expression; + + public virtual IQueryProvider Provider => GetQueryable().Provider; + + IEnumerator IEnumerable.GetEnumerator() + { + return GetEnumerator(); + } - protected RepositoryBase() + public IEnumerator GetEnumerator() { - CancellationTokenProvider = NullCancellationTokenProvider.Instance; + return GetQueryable().GetEnumerator(); } - public abstract List GetList(); + protected abstract IQueryable GetQueryable(); - public virtual Task> GetListAsync(CancellationToken cancellationToken = default) + public virtual void Delete(Expression> predicate) { - return Task.FromResult(GetList()); + foreach (var entity in GetQueryable().Where(predicate).ToList()) + { + Delete(entity); + } } - public virtual TEntity Get(TPrimaryKey id) + public virtual Task DeleteAsync(Expression> predicate, CancellationToken cancellationToken = default) { - var entity = Find(id); + Delete(predicate); + return Task.CompletedTask; + } - if (entity == null) + //TODO: Is that needed..? + protected virtual IQueryable ApplyDataFilters(IQueryable query) + { + if (typeof(ISoftDelete).IsAssignableFrom(typeof(TEntity))) { - throw new EntityNotFoundException(typeof(TEntity), id); + query = query.WhereIf(DataFilter.IsEnabled(), e => ((ISoftDelete)e).IsDeleted == false); } - return entity; + if (typeof(IMultiTenant).IsAssignableFrom(typeof(TEntity))) + { + var tenantId = CurrentTenant.Id; + query = query.WhereIf(DataFilter.IsEnabled(), e => ((IMultiTenant)e).TenantId == tenantId); + } + + return query; } + } - public virtual Task GetAsync(TPrimaryKey id, CancellationToken cancellationToken = default) + public abstract class RepositoryBase : RepositoryBase, IRepository + where TEntity : class, IEntity + { + public virtual TEntity Find(TKey id) { - return Task.FromResult(Get(id)); + return GetQueryable().FirstOrDefault(EntityHelper.CreateEqualityExpressionForId(id)); } - public abstract TEntity Find(TPrimaryKey id); - - public virtual Task FindAsync(TPrimaryKey id, CancellationToken cancellationToken = default) + public virtual TEntity Get(TKey id) { - return Task.FromResult(Find(id)); - } + var entity = Find(id); - public abstract TEntity Insert(TEntity entity, bool autoSave = false); + if (entity == null) + { + throw new EntityNotFoundException(typeof(TEntity), id); + } - public virtual Task InsertAsync(TEntity entity, bool autoSave = false, CancellationToken cancellationToken = default) - { - return Task.FromResult(Insert(entity, autoSave)); + return entity; } - public abstract TEntity Update(TEntity entity); - - public virtual Task UpdateAsync(TEntity entity, CancellationToken cancellationToken = default) + public virtual Task GetAsync(TKey id, CancellationToken cancellationToken = default) { - return Task.FromResult(Update(entity)); + return Task.FromResult(Get(id)); } - public abstract void Delete(TEntity entity); - - public virtual Task DeleteAsync(TEntity entity, CancellationToken cancellationToken = default) + public virtual Task FindAsync(TKey id, CancellationToken cancellationToken = default) { - Delete(entity); - return Task.CompletedTask; + return Task.FromResult(Find(id)); } - public virtual void Delete(TPrimaryKey id) + public virtual void Delete(TKey id) { var entity = Find(id); if (entity == null) @@ -88,29 +109,10 @@ namespace Volo.Abp.Domain.Repositories Delete(entity); } - public virtual Task DeleteAsync(TPrimaryKey id, CancellationToken cancellationToken = default) + public virtual Task DeleteAsync(TKey id, CancellationToken cancellationToken = default) { Delete(id); return Task.CompletedTask; } - - public abstract long GetCount(); - - public virtual Task GetCountAsync(CancellationToken cancellationToken = default) - { - return Task.FromResult(GetCount()); - } - - protected static Expression> CreateEqualityExpressionForId(TPrimaryKey id) - { - var lambdaParam = Expression.Parameter(typeof(TEntity)); - - var lambdaBody = Expression.Equal( - Expression.PropertyOrField(lambdaParam, "Id"), - Expression.Constant(id, typeof(TPrimaryKey)) - ); - - return Expression.Lambda>(lambdaBody, lambdaParam); - } } -} +} \ No newline at end of file diff --git a/src/Volo.Abp.Ddd/Volo/Abp/Domain/Repositories/RepositoryExtensions.cs b/src/Volo.Abp.Ddd/Volo/Abp/Domain/Repositories/RepositoryExtensions.cs index 3c9a503780..029ee5cd3c 100644 --- a/src/Volo.Abp.Ddd/Volo/Abp/Domain/Repositories/RepositoryExtensions.cs +++ b/src/Volo.Abp.Ddd/Volo/Abp/Domain/Repositories/RepositoryExtensions.cs @@ -11,55 +11,55 @@ namespace Volo.Abp.Domain.Repositories { public static class RepositoryExtensions { - public static async Task EnsureCollectionLoadedAsync( - this IRepository repository, + public static async Task EnsureCollectionLoadedAsync( + this IBasicRepository repository, TEntity entity, Expression>> propertyExpression, CancellationToken cancellationToken = default ) - where TEntity : class, IEntity + where TEntity : class, IEntity where TProperty : class { - var repo = ProxyHelper.UnProxy(repository) as ISupportsExplicitLoading; + var repo = ProxyHelper.UnProxy(repository) as ISupportsExplicitLoading; if (repo != null) { await repo.EnsureCollectionLoadedAsync(entity, propertyExpression, cancellationToken); } } - public static void EnsureCollectionLoaded( - this IRepository repository, + public static void EnsureCollectionLoaded( + this IBasicRepository repository, TEntity entity, Expression>> propertyExpression ) - where TEntity : class, IEntity + where TEntity : class, IEntity where TProperty : class { AsyncHelper.RunSync(() => repository.EnsureCollectionLoadedAsync(entity, propertyExpression)); } - public static async Task EnsurePropertyLoadedAsync( - this IRepository repository, + public static async Task EnsurePropertyLoadedAsync( + this IBasicRepository repository, TEntity entity, Expression> propertyExpression, CancellationToken cancellationToken = default ) - where TEntity : class, IEntity + where TEntity : class, IEntity where TProperty : class { - var repo = ProxyHelper.UnProxy(repository) as ISupportsExplicitLoading; + var repo = ProxyHelper.UnProxy(repository) as ISupportsExplicitLoading; if (repo != null) { await repo.EnsurePropertyLoadedAsync(entity, propertyExpression, cancellationToken); } } - public static void EnsurePropertyLoaded( - this IRepository repository, + public static void EnsurePropertyLoaded( + this IBasicRepository repository, TEntity entity, Expression> propertyExpression ) - where TEntity : class, IEntity + where TEntity : class, IEntity where TProperty : class { AsyncHelper.RunSync(() => repository.EnsurePropertyLoadedAsync(entity, propertyExpression)); diff --git a/src/Volo.Abp.Ddd/Volo/Abp/Domain/Repositories/RepositoryRegistrarBase.cs b/src/Volo.Abp.Ddd/Volo/Abp/Domain/Repositories/RepositoryRegistrarBase.cs index ea3e1963f8..addae8de35 100644 --- a/src/Volo.Abp.Ddd/Volo/Abp/Domain/Repositories/RepositoryRegistrarBase.cs +++ b/src/Volo.Abp.Ddd/Volo/Abp/Domain/Repositories/RepositoryRegistrarBase.cs @@ -3,7 +3,6 @@ using System.Collections.Generic; using Microsoft.Extensions.DependencyInjection; using Volo.Abp.DependencyInjection; using Volo.Abp.Domain.Entities; -using Volo.Abp.Reflection; namespace Volo.Abp.Domain.Repositories { @@ -45,24 +44,26 @@ namespace Volo.Abp.Domain.Repositories protected void RegisterDefaultRepository(IServiceCollection services, Type entityType) { - var primaryKeyType = EntityHelper.GetPrimaryKeyType(entityType); - var isDefaultPrimaryKey = primaryKeyType == typeof(Guid); + services.AddDefaultRepository( + entityType, + GetDefaultRepositoryImplementationType(entityType) + ); + } - Type repositoryImplementationType; - if (Options.SpecifiedDefaultRepositoryTypes) - { - repositoryImplementationType = isDefaultPrimaryKey - ? Options.DefaultRepositoryImplementationTypeWithDefaultPrimaryKey.MakeGenericType(entityType) - : Options.DefaultRepositoryImplementationType.MakeGenericType(entityType, primaryKeyType); - } - else + private Type GetDefaultRepositoryImplementationType(Type entityType) + { + var primaryKeyType = EntityHelper.FindPrimaryKeyType(entityType); + + if (primaryKeyType == null) { - repositoryImplementationType = isDefaultPrimaryKey - ? GetRepositoryTypeForDefaultPk(Options.DefaultRepositoryDbContextType, entityType) - : GetRepositoryType(Options.DefaultRepositoryDbContextType, entityType, primaryKeyType); + return Options.SpecifiedDefaultRepositoryTypes + ? Options.DefaultRepositoryImplementationTypeWithouTKey.MakeGenericType(entityType) + : GetRepositoryType(Options.DefaultRepositoryDbContextType, entityType); } - services.AddDefaultRepository(entityType, repositoryImplementationType); + return Options.SpecifiedDefaultRepositoryTypes + ? Options.DefaultRepositoryImplementationType.MakeGenericType(entityType, primaryKeyType) + : GetRepositoryType(Options.DefaultRepositoryDbContextType, entityType, primaryKeyType); } public bool ShouldRegisterDefaultRepositoryFor(Type entityType) @@ -77,7 +78,7 @@ namespace Volo.Abp.Domain.Repositories return false; } - if (!Options.IncludeAllEntitiesForDefaultRepositories && !ReflectionHelper.IsAssignableToGenericType(entityType, typeof(IAggregateRoot<>))) + if (!Options.IncludeAllEntitiesForDefaultRepositories && !typeof(IAggregateRoot).IsAssignableFrom(entityType)) { return false; } @@ -87,7 +88,7 @@ namespace Volo.Abp.Domain.Repositories protected abstract IEnumerable GetEntityTypes(Type dbContextType); - protected abstract Type GetRepositoryTypeForDefaultPk(Type dbContextType, Type entityType); + protected abstract Type GetRepositoryType(Type dbContextType, Type entityType); protected abstract Type GetRepositoryType(Type dbContextType, Type entityType, Type primaryKeyType); } diff --git a/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/Domain/Repositories/EfCoreRepositoryExtensions.cs b/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/Domain/Repositories/EfCoreRepositoryExtensions.cs index 84471504f7..a76136dc7b 100644 --- a/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/Domain/Repositories/EfCoreRepositoryExtensions.cs +++ b/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/Domain/Repositories/EfCoreRepositoryExtensions.cs @@ -7,25 +7,25 @@ namespace Volo.Abp.Domain.Repositories { public static class EfCoreRepositoryExtensions { - public static DbContext GetDbContext(this IRepository repository) - where TEntity : class, IEntity + public static DbContext GetDbContext(this IBasicRepository repository) + where TEntity : class, IEntity { return repository.ToEfCoreRepository().DbContext; } - public static DbSet GetDbSet(this IRepository repository) - where TEntity : class, IEntity + public static DbSet GetDbSet(this IBasicRepository repository) + where TEntity : class, IEntity { return repository.ToEfCoreRepository().DbSet; } - public static IEfCoreRepository ToEfCoreRepository(this IRepository repository) - where TEntity : class, IEntity + public static IEfCoreRepository ToEfCoreRepository(this IBasicRepository repository) + where TEntity : class, IEntity { - var efCoreRepository = repository as IEfCoreRepository; + var efCoreRepository = repository as IEfCoreRepository; if (efCoreRepository == null) { - throw new ArgumentException("Given repository does not implement " + typeof(IEfCoreRepository).AssemblyQualifiedName, nameof(repository)); + throw new ArgumentException("Given repository does not implement " + typeof(IEfCoreRepository).AssemblyQualifiedName, nameof(repository)); } return efCoreRepository; diff --git a/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/Domain/Repositories/EntityFrameworkCore/EfCoreRepository.cs b/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/Domain/Repositories/EntityFrameworkCore/EfCoreRepository.cs index 869d090176..d30bd6115e 100644 --- a/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/Domain/Repositories/EntityFrameworkCore/EfCoreRepository.cs +++ b/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/Domain/Repositories/EntityFrameworkCore/EfCoreRepository.cs @@ -7,30 +7,16 @@ using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Volo.Abp.Domain.Entities; using Volo.Abp.EntityFrameworkCore; -using Volo.Abp.Threading; namespace Volo.Abp.Domain.Repositories.EntityFrameworkCore { - public class EfCoreRepository : EfCoreRepository, IEfCoreRepository + public class EfCoreRepository : RepositoryBase, IEfCoreRepository where TDbContext : IEfCoreDbContext - where TEntity : class, IEntity - { - public EfCoreRepository(IDbContextProvider dbContextProvider) - : base(dbContextProvider) - { - } - } - - public class EfCoreRepository : QueryableRepositoryBase, - IEfCoreRepository, - ISupportsExplicitLoading - - where TDbContext : IEfCoreDbContext - where TEntity : class, IEntity + where TEntity : class, IEntity { public virtual DbSet DbSet => DbContext.Set(); - DbContext IEfCoreRepository.DbContext => DbContext.As(); + DbContext IEfCoreRepository.DbContext => DbContext.As(); protected virtual TDbContext DbContext => _dbContextProvider.GetDbContext(); @@ -40,39 +26,7 @@ namespace Volo.Abp.Domain.Repositories.EntityFrameworkCore { _dbContextProvider = dbContextProvider; } - - protected override IQueryable GetQueryable() - { - return DbSet.AsQueryable(); - } - - public override Task> GetListAsync(CancellationToken cancellationToken = default) - { - return DbSet.ToListAsync(CancellationTokenProvider.FallbackToProvider(cancellationToken)); - } - - public override async Task GetAsync(TPrimaryKey id, CancellationToken cancellationToken = default) - { - var entity = await FindAsync(id, CancellationTokenProvider.FallbackToProvider(cancellationToken)); - - if (entity == null) - { - throw new EntityNotFoundException(typeof(TEntity), id); - } - - return entity; - } - - public override TEntity Find(TPrimaryKey id) - { - return DbSet.Find(id); - } - - public override Task FindAsync(TPrimaryKey id, CancellationToken cancellationToken = default) - { - return DbSet.FindAsync(new object[] { id }, CancellationTokenProvider.FallbackToProvider(cancellationToken)); - } - + public override TEntity Insert(TEntity entity, bool autoSave = false) { var savedEntity = DbSet.Add(entity).Entity; @@ -91,7 +45,7 @@ namespace Volo.Abp.Domain.Repositories.EntityFrameworkCore if (autoSave) { - await DbContext.SaveChangesAsync(CancellationTokenProvider.FallbackToProvider(cancellationToken)); + await DbContext.SaveChangesAsync(GetCancellationToken(cancellationToken)); } return savedEntity; @@ -108,27 +62,27 @@ namespace Volo.Abp.Domain.Repositories.EntityFrameworkCore DbSet.Remove(entity); } + protected override IQueryable GetQueryable() + { + return DbSet.AsQueryable(); + } + public override async Task DeleteAsync(Expression> predicate, CancellationToken cancellationToken = default) { - var entities = await GetQueryable().Where(predicate).ToListAsync(CancellationTokenProvider.FallbackToProvider(cancellationToken)); + var entities = await GetQueryable().Where(predicate).ToListAsync(GetCancellationToken(cancellationToken)); foreach (var entity in entities) { DbSet.Remove(entity); } } - public override Task GetCountAsync(CancellationToken cancellationToken = default) - { - return GetQueryable().LongCountAsync(CancellationTokenProvider.FallbackToProvider(cancellationToken)); - } - public virtual Task EnsureCollectionLoadedAsync( TEntity entity, Expression>> propertyExpression, CancellationToken cancellationToken = default) where TProperty : class { - return DbContext.Entry(entity).Collection(propertyExpression).LoadAsync(CancellationTokenProvider.FallbackToProvider(cancellationToken)); + return DbContext.Entry(entity).Collection(propertyExpression).LoadAsync(GetCancellationToken(cancellationToken)); } public virtual Task EnsurePropertyLoadedAsync( @@ -137,7 +91,72 @@ namespace Volo.Abp.Domain.Repositories.EntityFrameworkCore CancellationToken cancellationToken = default) where TProperty : class { - return DbContext.Entry(entity).Reference(propertyExpression).LoadAsync(CancellationTokenProvider.FallbackToProvider(cancellationToken)); + return DbContext.Entry(entity).Reference(propertyExpression).LoadAsync(GetCancellationToken(cancellationToken)); + } + } + + public class EfCoreRepository : EfCoreRepository, + IEfCoreRepository, + ISupportsExplicitLoading + + where TDbContext : IEfCoreDbContext + where TEntity : class, IEntity + { + public EfCoreRepository(IDbContextProvider dbContextProvider) + : base(dbContextProvider) + { + + } + + public TEntity Get(TKey id) + { + var entity = Find(id); + + if (entity == null) + { + throw new EntityNotFoundException(typeof(TEntity), id); + } + + return entity; + } + + public virtual async Task GetAsync(TKey id, CancellationToken cancellationToken = default) + { + var entity = await FindAsync(id, GetCancellationToken(cancellationToken)); + + if (entity == null) + { + throw new EntityNotFoundException(typeof(TEntity), id); + } + + return entity; + } + + public virtual TEntity Find(TKey id) + { + return DbSet.Find(id); + } + + public virtual Task FindAsync(TKey id, CancellationToken cancellationToken = default) + { + return DbSet.FindAsync(new object[] { id }, GetCancellationToken(cancellationToken)); + } + + public virtual void Delete(TKey id) + { + var entity = Find(id); + if (entity == null) + { + return; + } + + Delete(entity); + } + + public virtual Task DeleteAsync(TKey id, CancellationToken cancellationToken = default) + { + Delete(id); + return Task.CompletedTask; } } } diff --git a/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/Domain/Repositories/EntityFrameworkCore/IEfCoreRepository.cs b/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/Domain/Repositories/EntityFrameworkCore/IEfCoreRepository.cs index e7e6ab171f..31a78f744d 100644 --- a/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/Domain/Repositories/EntityFrameworkCore/IEfCoreRepository.cs +++ b/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/Domain/Repositories/EntityFrameworkCore/IEfCoreRepository.cs @@ -1,20 +1,19 @@ -using System; using Microsoft.EntityFrameworkCore; using Volo.Abp.Domain.Entities; namespace Volo.Abp.Domain.Repositories.EntityFrameworkCore { - public interface IEfCoreRepository : IEfCoreRepository, IQueryableRepository - where TEntity : class, IEntity + public interface IEfCoreRepository : IRepository + where TEntity : class, IEntity { - + DbContext DbContext { get; } + + DbSet DbSet { get; } } - public interface IEfCoreRepository : IQueryableRepository - where TEntity : class, IEntity + public interface IEfCoreRepository : IEfCoreRepository, IRepository + where TEntity : class, IEntity { - DbContext DbContext { get; } - DbSet DbSet { get; } } } \ No newline at end of file diff --git a/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/DbContextHelper.cs b/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/DbContextHelper.cs index 06887c83c8..7c3a8707d4 100644 --- a/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/DbContextHelper.cs +++ b/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/DbContextHelper.cs @@ -16,7 +16,7 @@ namespace Volo.Abp.EntityFrameworkCore from property in dbContextType.GetTypeInfo().GetProperties(BindingFlags.Public | BindingFlags.Instance) where ReflectionHelper.IsAssignableToGenericType(property.PropertyType, typeof(DbSet<>)) && - ReflectionHelper.IsAssignableToGenericType(property.PropertyType.GenericTypeArguments[0], typeof(IEntity<>)) + typeof(IEntity).IsAssignableFrom(property.PropertyType.GenericTypeArguments[0]) select property.PropertyType.GenericTypeArguments[0]; } } diff --git a/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/DependencyInjection/EfCoreRepositoryRegistrar.cs b/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/DependencyInjection/EfCoreRepositoryRegistrar.cs index f481fadc69..f75c4a0132 100644 --- a/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/DependencyInjection/EfCoreRepositoryRegistrar.cs +++ b/src/Volo.Abp.EntityFrameworkCore/Volo/Abp/EntityFrameworkCore/DependencyInjection/EfCoreRepositoryRegistrar.cs @@ -17,7 +17,7 @@ namespace Volo.Abp.EntityFrameworkCore.DependencyInjection return DbContextHelper.GetEntityTypes(dbContextType); } - protected override Type GetRepositoryTypeForDefaultPk(Type dbContextType, Type entityType) + protected override Type GetRepositoryType(Type dbContextType, Type entityType) { return typeof(EfCoreRepository<,>).MakeGenericType(dbContextType, entityType); } diff --git a/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityRoleDto.cs b/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityRoleDto.cs index cb48f53146..13aa96f41b 100644 --- a/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityRoleDto.cs +++ b/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityRoleDto.cs @@ -1,8 +1,9 @@ -using Volo.Abp.Application.Dtos; +using System; +using Volo.Abp.Application.Dtos; namespace Volo.Abp.Identity { - public class IdentityRoleDto : EntityDto + public class IdentityRoleDto : EntityDto { public string Name { get; set; } } diff --git a/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityUserDto.cs b/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityUserDto.cs index d2721a1911..a5a549545b 100644 --- a/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityUserDto.cs +++ b/src/Volo.Abp.Identity.Application.Contracts/Volo/Abp/Identity/IdentityUserDto.cs @@ -3,7 +3,7 @@ using Volo.Abp.Application.Dtos; namespace Volo.Abp.Identity { - public class IdentityUserDto : EntityDto + public class IdentityUserDto : EntityDto { public string UserName { get; set; } diff --git a/src/Volo.Abp.Identity.Application/Volo/Abp/Identity/IdentityRoleAppService.cs b/src/Volo.Abp.Identity.Application/Volo/Abp/Identity/IdentityRoleAppService.cs index 08b2ff4faa..f6bee59fa8 100644 --- a/src/Volo.Abp.Identity.Application/Volo/Abp/Identity/IdentityRoleAppService.cs +++ b/src/Volo.Abp.Identity.Application/Volo/Abp/Identity/IdentityRoleAppService.cs @@ -26,10 +26,10 @@ namespace Volo.Abp.Identity ); } - public async Task> GetListAsync(GetIdentityRolesInput input) + public async Task> GetListAsync(GetIdentityRolesInput input) //TODO: Remove input { - var count = (int)await _roleRepository.GetCountAsync(); - var list = await _roleRepository.GetListAsync(input.Sorting, input.MaxResultCount, input.SkipCount, input.Filter); + var count = (int) await _roleRepository.GetCountAsync(); + var list = await _roleRepository.GetListAsync(); return new PagedResultDto( count, diff --git a/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IIdentityRoleRepository.cs b/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IIdentityRoleRepository.cs index c6033714f8..b68ac92ccd 100644 --- a/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IIdentityRoleRepository.cs +++ b/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IIdentityRoleRepository.cs @@ -1,3 +1,4 @@ +using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; @@ -5,10 +6,12 @@ using Volo.Abp.Domain.Repositories; namespace Volo.Abp.Identity { - public interface IIdentityRoleRepository : IRepository + public interface IIdentityRoleRepository : IBasicRepository { Task FindByNormalizedNameAsync(string normalizedRoleName, CancellationToken cancellationToken); - Task> GetListAsync(string sorting, int maxResultCount, int skipCount, string filter); + Task> GetListAsync(string sorting = null, int maxResultCount = int.MaxValue, int skipCount = 0); + + Task GetCountAsync(CancellationToken cancellationToken = default); } } \ No newline at end of file diff --git a/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IIdentityUserRepository.cs b/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IIdentityUserRepository.cs index 39b1b649bb..0f6acf0151 100644 --- a/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IIdentityUserRepository.cs +++ b/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IIdentityUserRepository.cs @@ -8,25 +8,27 @@ using Volo.Abp.Domain.Repositories; namespace Volo.Abp.Identity { - public interface IIdentityUserRepository : IRepository + public interface IIdentityUserRepository : IBasicRepository { - Task FindByNormalizedUserNameAsync([NotNull] string normalizedUserName, CancellationToken cancellationToken); + Task FindByNormalizedUserNameAsync([NotNull] string normalizedUserName, CancellationToken cancellationToken = default); Task> GetRoleNamesAsync(Guid userId); - Task FindByLoginAsync([NotNull] string loginProvider, [NotNull] string providerKey, CancellationToken cancellationToken); + Task FindByLoginAsync([NotNull] string loginProvider, [NotNull] string providerKey, CancellationToken cancellationToken = default); - Task FindByNormalizedEmailAsync([NotNull] string normalizedEmail, CancellationToken cancellationToken); + Task FindByNormalizedEmailAsync([NotNull] string normalizedEmail, CancellationToken cancellationToken = default); //TODO: Why not return List instead of IList - Task> GetListByClaimAsync(Claim claim, CancellationToken cancellationToken); + Task> GetListByClaimAsync(Claim claim, CancellationToken cancellationToken = default); //TODO: Why not return List instead of IList - Task> GetListByNormalizedRoleNameAsync(string normalizedRoleName, CancellationToken cancellationToken); + Task> GetListByNormalizedRoleNameAsync(string normalizedRoleName, CancellationToken cancellationToken = default); //TODO: DTO can be used instead of parameters - Task> GetListAsync(string sorting, int maxResultCount, int skipCount, string filter); + Task> GetListAsync(string sorting, int maxResultCount, int skipCount, string filter, CancellationToken cancellationToken = default); Task> GetRolesAsync(Guid userId); + + Task GetCountAsync(CancellationToken cancellationToken = default); } } diff --git a/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityRole.cs b/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityRole.cs index d7054c95e5..fe6af2e7f6 100644 --- a/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityRole.cs +++ b/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityRole.cs @@ -11,7 +11,7 @@ namespace Volo.Abp.Identity /// /// Represents a role in the identity system /// - public class IdentityRole : AggregateRoot, IHasConcurrencyStamp + public class IdentityRole : AggregateRoot, IHasConcurrencyStamp { /// /// Gets or sets the name for this role. diff --git a/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityRoleClaim.cs b/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityRoleClaim.cs index d9860bff28..ec659f3f03 100644 --- a/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityRoleClaim.cs +++ b/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityRoleClaim.cs @@ -8,7 +8,7 @@ namespace Volo.Abp.Identity /// /// Represents a claim that is granted to all users within a role. /// - public class IdentityRoleClaim : Entity + public class IdentityRoleClaim : Entity { /// /// Gets or sets the of the primary key of the role associated with this claim. diff --git a/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUser.cs b/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUser.cs index fe039d2b00..4e3b7097ec 100644 --- a/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUser.cs +++ b/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUser.cs @@ -12,7 +12,7 @@ namespace Volo.Abp.Identity { //Add Name and Surname properties? - public class IdentityUser : AggregateRoot, IHasConcurrencyStamp + public class IdentityUser : AggregateRoot, IHasConcurrencyStamp { /// /// Gets or sets the user name for this user. diff --git a/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserClaim.cs b/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserClaim.cs index e505db833e..4129034547 100644 --- a/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserClaim.cs +++ b/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserClaim.cs @@ -8,7 +8,7 @@ namespace Volo.Abp.Identity /// /// Represents a claim that a user possesses. /// - public class IdentityUserClaim : Entity + public class IdentityUserClaim : Entity { /// /// Gets or sets the primary key of the user associated with this claim. diff --git a/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserLogin.cs b/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserLogin.cs index f4263445c3..8556fee9d7 100644 --- a/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserLogin.cs +++ b/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserLogin.cs @@ -8,7 +8,7 @@ namespace Volo.Abp.Identity /// /// Represents a login and its associated provider for a user. /// - public class IdentityUserLogin : Entity + public class IdentityUserLogin : Entity { /// /// Gets or sets the of the primary key of the user associated with this login. diff --git a/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserRole.cs b/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserRole.cs index 1867ec582e..2740b67323 100644 --- a/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserRole.cs +++ b/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserRole.cs @@ -6,7 +6,7 @@ namespace Volo.Abp.Identity /// /// Represents the link between a user and a role. /// - public class IdentityUserRole : Entity + public class IdentityUserRole : Entity { /// /// Gets or sets the primary key of the user that is linked to a role. diff --git a/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserToken.cs b/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserToken.cs index 2e1ed4d302..e37c5b9d43 100644 --- a/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserToken.cs +++ b/src/Volo.Abp.Identity.Domain/Volo/Abp/Identity/IdentityUserToken.cs @@ -7,7 +7,7 @@ namespace Volo.Abp.Identity /// /// Represents an authentication token for a user. /// - public class IdentityUserToken : Entity + public class IdentityUserToken : Entity { /// /// Gets or sets the primary key of the user that the token belongs to. diff --git a/src/Volo.Abp.Identity.EntityFrameworkCore/Volo.Abp.Identity.EntityFrameworkCore.csproj.DotSettings b/src/Volo.Abp.Identity.EntityFrameworkCore/Volo.Abp.Identity.EntityFrameworkCore.csproj.DotSettings new file mode 100644 index 0000000000..58ad6c8854 --- /dev/null +++ b/src/Volo.Abp.Identity.EntityFrameworkCore/Volo.Abp.Identity.EntityFrameworkCore.csproj.DotSettings @@ -0,0 +1,2 @@ + + CSharp71 \ No newline at end of file diff --git a/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EfCoreIdentityRoleRepository.cs b/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EfCoreIdentityRoleRepository.cs index 7ab50948e8..864db178e0 100644 --- a/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EfCoreIdentityRoleRepository.cs +++ b/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EfCoreIdentityRoleRepository.cs @@ -11,7 +11,7 @@ using System; namespace Volo.Abp.Identity { - public class EfCoreIdentityRoleRepository : EfCoreRepository, IIdentityRoleRepository + public class EfCoreIdentityRoleRepository : EfCoreRepository, IIdentityRoleRepository { public EfCoreIdentityRoleRepository(IDbContextProvider dbContextProvider) : base(dbContextProvider) @@ -23,13 +23,17 @@ namespace Volo.Abp.Identity return DbSet.FirstOrDefaultAsync(r => r.NormalizedName == normalizedRoleName, cancellationToken); } - public async Task> GetListAsync(string sorting, int maxResultCount, int skipCount, string filter) + public async Task> GetListAsync(string sorting = null, int maxResultCount = int.MaxValue, int skipCount = 0) { - return await this.WhereIf( - !filter.IsNullOrWhiteSpace(), - r => r.Name.Contains(filter) - ).OrderBy(sorting ?? nameof(IdentityRole.Name)) - .PageBy(skipCount, maxResultCount).ToListAsync(); + return await this + .OrderBy(sorting ?? nameof(IdentityRole.Name)) + .PageBy(skipCount, maxResultCount) + .ToListAsync(); + } + + public async Task GetCountAsync(CancellationToken cancellationToken = default) + { + return await this.LongCountAsync(cancellationToken); } } } \ No newline at end of file diff --git a/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EfCoreIdentityUserRepository.cs b/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EfCoreIdentityUserRepository.cs index 8deac6bef1..a9e4c553df 100644 --- a/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EfCoreIdentityUserRepository.cs +++ b/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EfCoreIdentityUserRepository.cs @@ -12,7 +12,7 @@ using Volo.Abp.Identity.EntityFrameworkCore; namespace Volo.Abp.Identity { - public class EfCoreIdentityUserRepository : EfCoreRepository, IIdentityUserRepository + public class EfCoreIdentityUserRepository : EfCoreRepository, IIdentityUserRepository { public EfCoreIdentityUserRepository(IDbContextProvider dbContextProvider) : base(dbContextProvider) @@ -81,7 +81,7 @@ namespace Volo.Abp.Identity return await query.ToListAsync(cancellationToken); } - public async Task> GetListAsync(string sorting, int maxResultCount, int skipCount, string filter) + public async Task> GetListAsync(string sorting, int maxResultCount, int skipCount, string filter, CancellationToken cancellationToken = default) { return await this.WhereIf( !filter.IsNullOrWhiteSpace(), @@ -90,7 +90,7 @@ namespace Volo.Abp.Identity u.Email.Contains(filter) ) .OrderBy(sorting ?? nameof(IdentityUser.UserName)) - .PageBy(skipCount, maxResultCount).ToListAsync(); + .PageBy(skipCount, maxResultCount).ToListAsync(cancellationToken); } public async Task> GetListAsync(string sorting, int maxResultCount, int skipCount) @@ -107,5 +107,10 @@ namespace Volo.Abp.Identity return await query.ToListAsync(); } + + public async Task GetCountAsync(CancellationToken cancellationToken = default) + { + return await this.LongCountAsync(cancellationToken); + } } } diff --git a/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EntityFrameworkCore/AbpIdentityEntityFrameworkCoreModule.cs b/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EntityFrameworkCore/AbpIdentityEntityFrameworkCoreModule.cs index fb3d42cb30..9951d6564b 100644 --- a/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EntityFrameworkCore/AbpIdentityEntityFrameworkCoreModule.cs +++ b/src/Volo.Abp.Identity.EntityFrameworkCore/Volo/Abp/Identity/EntityFrameworkCore/AbpIdentityEntityFrameworkCoreModule.cs @@ -12,8 +12,8 @@ namespace Volo.Abp.Identity.EntityFrameworkCore services.AddAbpDbContext(options => { options.AddDefaultRepositories(); - options.AddCustomRepository(); - options.AddCustomRepository(); + options.AddRepository(); + options.AddRepository(); }); services.AddAssemblyOf(); diff --git a/src/Volo.Abp.IdentityServer.Domain/Volo.Abp.IdentityServer.Domain.csproj.DotSettings b/src/Volo.Abp.IdentityServer.Domain/Volo.Abp.IdentityServer.Domain.csproj.DotSettings new file mode 100644 index 0000000000..58ad6c8854 --- /dev/null +++ b/src/Volo.Abp.IdentityServer.Domain/Volo.Abp.IdentityServer.Domain.csproj.DotSettings @@ -0,0 +1,2 @@ + + CSharp71 \ No newline at end of file diff --git a/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/ApiResources/ApiResource.cs b/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/ApiResources/ApiResource.cs index 2bd9339c13..73eb194e5f 100644 --- a/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/ApiResources/ApiResource.cs +++ b/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/ApiResources/ApiResource.cs @@ -5,7 +5,7 @@ using Volo.Abp.Domain.Entities; namespace Volo.Abp.IdentityServer.ApiResources { - public class ApiResource : AggregateRoot + public class ApiResource : AggregateRoot { public virtual bool Enabled { get; set; } diff --git a/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/ApiResources/ApiScope.cs b/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/ApiResources/ApiScope.cs index ab4056d657..9512190497 100644 --- a/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/ApiResources/ApiScope.cs +++ b/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/ApiResources/ApiScope.cs @@ -4,7 +4,7 @@ using Volo.Abp.Domain.Entities; namespace Volo.Abp.IdentityServer.ApiResources { - public class ApiScope : Entity + public class ApiScope : Entity { public virtual string Name { get; set; } diff --git a/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/ApiResources/IApiResourceRepository.cs b/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/ApiResources/IApiResourceRepository.cs index 759bbbdf02..0050584088 100644 --- a/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/ApiResources/IApiResourceRepository.cs +++ b/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/ApiResources/IApiResourceRepository.cs @@ -1,9 +1,12 @@ -using Volo.Abp.Domain.Repositories; +using System; +using System.Threading; +using System.Threading.Tasks; +using Volo.Abp.Domain.Repositories; namespace Volo.Abp.IdentityServer.ApiResources { - public interface IApiResourceRepository : IRepository + public interface IApiResourceRepository : IBasicRepository { - + Task FindByNameAsync(string name, CancellationToken cancellationToken = default); } } \ No newline at end of file diff --git a/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Clients/Client.cs b/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Clients/Client.cs index 17b35d1a05..2154495e18 100644 --- a/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Clients/Client.cs +++ b/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Clients/Client.cs @@ -8,7 +8,7 @@ using Volo.Abp.Guids; namespace Volo.Abp.IdentityServer.Clients { - public class Client : AggregateRoot + public class Client : AggregateRoot { public virtual string ClientId { get; set; } diff --git a/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Clients/ClientClaim.cs b/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Clients/ClientClaim.cs index bb0cb7e0f5..ef1330d412 100644 --- a/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Clients/ClientClaim.cs +++ b/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Clients/ClientClaim.cs @@ -3,7 +3,7 @@ using Volo.Abp.Domain.Entities; namespace Volo.Abp.IdentityServer.Clients { - public class ClientClaim : Entity + public class ClientClaim : Entity { public virtual string Type { get; set; } diff --git a/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Clients/ClientCorsOrigin.cs b/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Clients/ClientCorsOrigin.cs index 4decc3132e..91d55c3348 100644 --- a/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Clients/ClientCorsOrigin.cs +++ b/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Clients/ClientCorsOrigin.cs @@ -3,7 +3,7 @@ using Volo.Abp.Domain.Entities; namespace Volo.Abp.IdentityServer.Clients { - public class ClientCorsOrigin : Entity + public class ClientCorsOrigin : Entity { public virtual string Origin { get; set; } diff --git a/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Clients/ClientIdPRestriction.cs b/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Clients/ClientIdPRestriction.cs index 936dc71042..9515d1fb88 100644 --- a/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Clients/ClientIdPRestriction.cs +++ b/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Clients/ClientIdPRestriction.cs @@ -3,7 +3,7 @@ using Volo.Abp.Domain.Entities; namespace Volo.Abp.IdentityServer.Clients { - public class ClientIdPRestriction : Entity + public class ClientIdPRestriction : Entity { public virtual string Provider { get; set; } diff --git a/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Clients/ClientPostLogoutRedirectUri.cs b/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Clients/ClientPostLogoutRedirectUri.cs index fa30e00819..a1e0230f2a 100644 --- a/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Clients/ClientPostLogoutRedirectUri.cs +++ b/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Clients/ClientPostLogoutRedirectUri.cs @@ -3,7 +3,7 @@ using Volo.Abp.Domain.Entities; namespace Volo.Abp.IdentityServer.Clients { - public class ClientPostLogoutRedirectUri : Entity + public class ClientPostLogoutRedirectUri : Entity { public virtual string PostLogoutRedirectUri { get; set; } diff --git a/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Clients/ClientProperty.cs b/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Clients/ClientProperty.cs index 843884cf3b..da6174d366 100644 --- a/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Clients/ClientProperty.cs +++ b/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Clients/ClientProperty.cs @@ -3,7 +3,7 @@ using Volo.Abp.Domain.Entities; namespace Volo.Abp.IdentityServer.Clients { - public class ClientProperty : Entity + public class ClientProperty : Entity { public virtual string Key { get; set; } diff --git a/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Clients/ClientRedirectUri.cs b/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Clients/ClientRedirectUri.cs index 689d15a681..073aae7c48 100644 --- a/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Clients/ClientRedirectUri.cs +++ b/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Clients/ClientRedirectUri.cs @@ -3,7 +3,7 @@ using Volo.Abp.Domain.Entities; namespace Volo.Abp.IdentityServer.Clients { - public class ClientRedirectUri : Entity + public class ClientRedirectUri : Entity { public virtual string RedirectUri { get; set; } diff --git a/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Clients/ClientScope.cs b/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Clients/ClientScope.cs index e28d33cacb..07e038ca5e 100644 --- a/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Clients/ClientScope.cs +++ b/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Clients/ClientScope.cs @@ -3,7 +3,7 @@ using Volo.Abp.Domain.Entities; namespace Volo.Abp.IdentityServer.Clients { - public class ClientScope : Entity + public class ClientScope : Entity { public virtual string Scope { get; protected set; } diff --git a/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Clients/IClientRepository.cs b/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Clients/IClientRepository.cs index c8cd46af63..df5bc2bd43 100644 --- a/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Clients/IClientRepository.cs +++ b/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Clients/IClientRepository.cs @@ -1,10 +1,11 @@ -using System.Threading.Tasks; +using System; +using System.Threading.Tasks; using JetBrains.Annotations; using Volo.Abp.Domain.Repositories; namespace Volo.Abp.IdentityServer.Clients { - public interface IClientRepository : IRepository + public interface IClientRepository : IBasicRepository { Task FindByCliendIdIncludingAllAsync([NotNull] string clientId); } diff --git a/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Grants/IPersistentGrantRepository.cs b/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Grants/IPersistentGrantRepository.cs index 709fe00d62..414484bc51 100644 --- a/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Grants/IPersistentGrantRepository.cs +++ b/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Grants/IPersistentGrantRepository.cs @@ -1,10 +1,11 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Threading.Tasks; using Volo.Abp.Domain.Repositories; namespace Volo.Abp.IdentityServer.Grants { - public interface IPersistentGrantRepository : IRepository + public interface IPersistentGrantRepository : IBasicRepository { Task FindByKeyAsync(string key); diff --git a/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Grants/PersistedGrant.cs b/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Grants/PersistedGrant.cs index e47401d607..4a2bccd456 100644 --- a/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Grants/PersistedGrant.cs +++ b/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Grants/PersistedGrant.cs @@ -3,7 +3,7 @@ using Volo.Abp.Domain.Entities; namespace Volo.Abp.IdentityServer.Grants { - public class PersistedGrant : AggregateRoot + public class PersistedGrant : AggregateRoot { public virtual string Key { get; set; } diff --git a/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Grants/PersistedGrantStore.cs b/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Grants/PersistedGrantStore.cs index f312132900..31ab551053 100644 --- a/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Grants/PersistedGrantStore.cs +++ b/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Grants/PersistedGrantStore.cs @@ -1,10 +1,8 @@ using System.Collections.Generic; using System.Linq; -using System.Linq.Dynamic.Core; using System.Threading.Tasks; using IdentityServer4.Stores; using Volo.Abp.DependencyInjection; -using Volo.Abp.Domain.Repositories; using Volo.Abp.ObjectMapping; namespace Volo.Abp.IdentityServer.Grants diff --git a/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/IdentityResources/IIdentityResourceRepository.cs b/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/IdentityResources/IIdentityResourceRepository.cs index 94b86754da..ea207fc9f1 100644 --- a/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/IdentityResources/IIdentityResourceRepository.cs +++ b/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/IdentityResources/IIdentityResourceRepository.cs @@ -1,11 +1,12 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Threading.Tasks; using Volo.Abp.Domain.Repositories; using ApiResource = Volo.Abp.IdentityServer.ApiResources.ApiResource; namespace Volo.Abp.IdentityServer.IdentityResources { - public interface IIdentityResourceRepository : IRepository + public interface IIdentityResourceRepository : IBasicRepository { Task> FindIdentityResourcesByScopeAsync(string[] scopeNames); diff --git a/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/IdentityResources/IdentityResource.cs b/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/IdentityResources/IdentityResource.cs index 9251862c96..04dcd847ca 100644 --- a/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/IdentityResources/IdentityResource.cs +++ b/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/IdentityResources/IdentityResource.cs @@ -4,7 +4,7 @@ using Volo.Abp.Domain.Entities; namespace Volo.Abp.IdentityServer.IdentityResources { - public class IdentityResource : AggregateRoot + public class IdentityResource : AggregateRoot { public virtual bool Enabled { get; set; } = true; diff --git a/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Secret.cs b/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Secret.cs index 6e7f753124..45302a97f8 100644 --- a/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Secret.cs +++ b/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/Secret.cs @@ -6,7 +6,7 @@ namespace Volo.Abp.IdentityServer { //TODO: Eleminate Secret class for simplicity. - public abstract class Secret : Entity + public abstract class Secret : Entity { public virtual string Description { get; protected set; } diff --git a/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/UserClaim.cs b/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/UserClaim.cs index 9529a42ed1..f6d911d547 100644 --- a/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/UserClaim.cs +++ b/src/Volo.Abp.IdentityServer.Domain/Volo/Abp/IdentityServer/UserClaim.cs @@ -5,7 +5,7 @@ namespace Volo.Abp.IdentityServer { //TODO: Eleminate UserClaim class for simplicity. - public abstract class UserClaim : Entity + public abstract class UserClaim : Entity { public virtual string Type { get; set; } diff --git a/src/Volo.Abp.IdentityServer.EntityFrameworkCore/Volo.Abp.IdentityServer.EntityFrameworkCore.csproj.DotSettings b/src/Volo.Abp.IdentityServer.EntityFrameworkCore/Volo.Abp.IdentityServer.EntityFrameworkCore.csproj.DotSettings new file mode 100644 index 0000000000..58ad6c8854 --- /dev/null +++ b/src/Volo.Abp.IdentityServer.EntityFrameworkCore/Volo.Abp.IdentityServer.EntityFrameworkCore.csproj.DotSettings @@ -0,0 +1,2 @@ + + CSharp71 \ No newline at end of file diff --git a/src/Volo.Abp.IdentityServer.EntityFrameworkCore/Volo/Abp/IdentityServer/ApiResourceRepository.cs b/src/Volo.Abp.IdentityServer.EntityFrameworkCore/Volo/Abp/IdentityServer/ApiResourceRepository.cs index bd62b96b6b..49e0715fb2 100644 --- a/src/Volo.Abp.IdentityServer.EntityFrameworkCore/Volo/Abp/IdentityServer/ApiResourceRepository.cs +++ b/src/Volo.Abp.IdentityServer.EntityFrameworkCore/Volo/Abp/IdentityServer/ApiResourceRepository.cs @@ -1,15 +1,24 @@ -using Volo.Abp.Domain.Repositories.EntityFrameworkCore; +using System; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.EntityFrameworkCore; +using Volo.Abp.Domain.Repositories.EntityFrameworkCore; using Volo.Abp.EntityFrameworkCore; using Volo.Abp.IdentityServer.ApiResources; using Volo.Abp.IdentityServer.EntityFrameworkCore; namespace Volo.Abp.IdentityServer { - public class ApiResourceRepository : EfCoreRepository, IApiResourceRepository + public class ApiResourceRepository : EfCoreRepository, IApiResourceRepository { public ApiResourceRepository(IDbContextProvider dbContextProvider) : base(dbContextProvider) { } + + public async Task FindByNameAsync(string name, CancellationToken cancellationToken = default) + { + return await this.FirstOrDefaultAsync(ar => ar.Name == name, cancellationToken); + } } } \ No newline at end of file diff --git a/src/Volo.Abp.IdentityServer.EntityFrameworkCore/Volo/Abp/IdentityServer/ClientRepository.cs b/src/Volo.Abp.IdentityServer.EntityFrameworkCore/Volo/Abp/IdentityServer/ClientRepository.cs index e0d44d2183..da142e91e9 100644 --- a/src/Volo.Abp.IdentityServer.EntityFrameworkCore/Volo/Abp/IdentityServer/ClientRepository.cs +++ b/src/Volo.Abp.IdentityServer.EntityFrameworkCore/Volo/Abp/IdentityServer/ClientRepository.cs @@ -1,4 +1,5 @@ -using System.Threading.Tasks; +using System; +using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; using Volo.Abp.Domain.Repositories.EntityFrameworkCore; using Volo.Abp.EntityFrameworkCore; @@ -7,7 +8,7 @@ using Volo.Abp.IdentityServer.EntityFrameworkCore; namespace Volo.Abp.IdentityServer { - public class ClientRepository : EfCoreRepository, IClientRepository + public class ClientRepository : EfCoreRepository, IClientRepository { public ClientRepository(IDbContextProvider dbContextProvider) : base(dbContextProvider) { diff --git a/src/Volo.Abp.IdentityServer.EntityFrameworkCore/Volo/Abp/IdentityServer/EntityFrameworkCore/AbpIdentityServerModule.cs b/src/Volo.Abp.IdentityServer.EntityFrameworkCore/Volo/Abp/IdentityServer/EntityFrameworkCore/AbpIdentityServerModule.cs index 1d53416680..d27afaf01d 100644 --- a/src/Volo.Abp.IdentityServer.EntityFrameworkCore/Volo/Abp/IdentityServer/EntityFrameworkCore/AbpIdentityServerModule.cs +++ b/src/Volo.Abp.IdentityServer.EntityFrameworkCore/Volo/Abp/IdentityServer/EntityFrameworkCore/AbpIdentityServerModule.cs @@ -14,7 +14,7 @@ namespace Volo.Abp.IdentityServer.EntityFrameworkCore services.AddAbpDbContext(options => { options.AddDefaultRepositories(); - options.AddCustomRepository(); + options.AddRepository(); }); services.AddAssemblyOf(); diff --git a/src/Volo.Abp.IdentityServer.EntityFrameworkCore/Volo/Abp/IdentityServer/IdentityResourceRepository.cs b/src/Volo.Abp.IdentityServer.EntityFrameworkCore/Volo/Abp/IdentityServer/IdentityResourceRepository.cs index ff49b87a8e..80659d6f28 100644 --- a/src/Volo.Abp.IdentityServer.EntityFrameworkCore/Volo/Abp/IdentityServer/IdentityResourceRepository.cs +++ b/src/Volo.Abp.IdentityServer.EntityFrameworkCore/Volo/Abp/IdentityServer/IdentityResourceRepository.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; @@ -13,7 +14,7 @@ namespace Volo.Abp.IdentityServer { //TODO: This is not true implementation! This repository works for 2 different aggregate root! - public class IdentityResourceRepository : EfCoreRepository, IIdentityResourceRepository + public class IdentityResourceRepository : EfCoreRepository, IIdentityResourceRepository { public IdentityResourceRepository(IDbContextProvider dbContextProvider) : base(dbContextProvider) diff --git a/src/Volo.Abp.IdentityServer.EntityFrameworkCore/Volo/Abp/IdentityServer/PersistedGrantRepository.cs b/src/Volo.Abp.IdentityServer.EntityFrameworkCore/Volo/Abp/IdentityServer/PersistedGrantRepository.cs index 0b1011992c..999192a27c 100644 --- a/src/Volo.Abp.IdentityServer.EntityFrameworkCore/Volo/Abp/IdentityServer/PersistedGrantRepository.cs +++ b/src/Volo.Abp.IdentityServer.EntityFrameworkCore/Volo/Abp/IdentityServer/PersistedGrantRepository.cs @@ -1,4 +1,5 @@ -using System.Collections.Generic; +using System; +using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore; @@ -9,7 +10,7 @@ using Volo.Abp.IdentityServer.Grants; namespace Volo.Abp.IdentityServer { - public class PersistentGrantRepository : EfCoreRepository, IPersistentGrantRepository + public class PersistentGrantRepository : EfCoreRepository, IPersistentGrantRepository { public PersistentGrantRepository(IDbContextProvider dbContextProvider) : base(dbContextProvider) { diff --git a/src/Volo.Abp.MemoryDb/Volo/Abp/Domain/Repositories/MemoryDb/IMemoryDatabase.cs b/src/Volo.Abp.MemoryDb/Volo/Abp/Domain/Repositories/MemoryDb/IMemoryDatabase.cs index 7cbaf15e70..1e6cd6f54c 100644 --- a/src/Volo.Abp.MemoryDb/Volo/Abp/Domain/Repositories/MemoryDb/IMemoryDatabase.cs +++ b/src/Volo.Abp.MemoryDb/Volo/Abp/Domain/Repositories/MemoryDb/IMemoryDatabase.cs @@ -6,6 +6,6 @@ namespace Volo.Abp.Domain.Repositories.MemoryDb { List Collection(); - TPrimaryKey GenerateNextId(); + TKey GenerateNextId(); } } \ No newline at end of file diff --git a/src/Volo.Abp.MemoryDb/Volo/Abp/Domain/Repositories/MemoryDb/IMemoryDbRepository.cs b/src/Volo.Abp.MemoryDb/Volo/Abp/Domain/Repositories/MemoryDb/IMemoryDbRepository.cs index 59f001195a..dd241b25a5 100644 --- a/src/Volo.Abp.MemoryDb/Volo/Abp/Domain/Repositories/MemoryDb/IMemoryDbRepository.cs +++ b/src/Volo.Abp.MemoryDb/Volo/Abp/Domain/Repositories/MemoryDb/IMemoryDbRepository.cs @@ -1,20 +1,19 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using Volo.Abp.Domain.Entities; namespace Volo.Abp.Domain.Repositories.MemoryDb { - public interface IMemoryDbRepository : IMemoryDbRepository, IQueryableRepository - where TEntity : class, IEntity + public interface IMemoryDbRepository : IRepository + where TEntity : class, IEntity { - + IMemoryDatabase Database { get; } + + List Collection { get; } } - public interface IMemoryDbRepository : IQueryableRepository - where TEntity : class, IEntity + public interface IMemoryDbRepository : IMemoryDbRepository, IRepository + where TEntity : class, IEntity { - IMemoryDatabase Database { get; } - List Collection { get; } } } diff --git a/src/Volo.Abp.MemoryDb/Volo/Abp/Domain/Repositories/MemoryDb/InMemoryIdGenerator.cs b/src/Volo.Abp.MemoryDb/Volo/Abp/Domain/Repositories/MemoryDb/InMemoryIdGenerator.cs index 1741d2cc02..467fff5bc5 100644 --- a/src/Volo.Abp.MemoryDb/Volo/Abp/Domain/Repositories/MemoryDb/InMemoryIdGenerator.cs +++ b/src/Volo.Abp.MemoryDb/Volo/Abp/Domain/Repositories/MemoryDb/InMemoryIdGenerator.cs @@ -8,24 +8,24 @@ namespace Volo.Abp.Domain.Repositories.MemoryDb private int _lastInt; private long _lastLong; - public TPrimaryKey GenerateNext() + public TKey GenerateNext() { - if (typeof(TPrimaryKey) == typeof(Guid)) + if (typeof(TKey) == typeof(Guid)) { - return (TPrimaryKey)(object)Guid.NewGuid(); + return (TKey)(object)Guid.NewGuid(); } - if (typeof(TPrimaryKey) == typeof(int)) + if (typeof(TKey) == typeof(int)) { - return (TPrimaryKey)(object)Interlocked.Increment(ref _lastInt); + return (TKey)(object)Interlocked.Increment(ref _lastInt); } - if (typeof(TPrimaryKey) == typeof(long)) + if (typeof(TKey) == typeof(long)) { - return (TPrimaryKey)(object)Interlocked.Increment(ref _lastLong); + return (TKey)(object)Interlocked.Increment(ref _lastLong); } - throw new AbpException("Not supported PrimaryKey type: " + typeof(TPrimaryKey).FullName); + throw new AbpException("Not supported PrimaryKey type: " + typeof(TKey).FullName); } } } \ No newline at end of file diff --git a/src/Volo.Abp.MemoryDb/Volo/Abp/Domain/Repositories/MemoryDb/MemoryDatabase.cs b/src/Volo.Abp.MemoryDb/Volo/Abp/Domain/Repositories/MemoryDb/MemoryDatabase.cs index 332138eae2..212c151087 100644 --- a/src/Volo.Abp.MemoryDb/Volo/Abp/Domain/Repositories/MemoryDb/MemoryDatabase.cs +++ b/src/Volo.Abp.MemoryDb/Volo/Abp/Domain/Repositories/MemoryDb/MemoryDatabase.cs @@ -21,11 +21,11 @@ namespace Volo.Abp.Domain.Repositories.MemoryDb return _sets.GetOrAdd(typeof(TEntity), _ => new List()) as List; } - public TPrimaryKey GenerateNextId() + public TKey GenerateNextId() { return _idGenerators .GetOrAdd(typeof(TEntity), () => new InMemoryIdGenerator()) - .GenerateNext(); + .GenerateNext(); } } } \ No newline at end of file diff --git a/src/Volo.Abp.MemoryDb/Volo/Abp/Domain/Repositories/MemoryDb/MemoryDbRepository.cs b/src/Volo.Abp.MemoryDb/Volo/Abp/Domain/Repositories/MemoryDb/MemoryDbRepository.cs index 01568ff066..e8fb1fb098 100644 --- a/src/Volo.Abp.MemoryDb/Volo/Abp/Domain/Repositories/MemoryDb/MemoryDbRepository.cs +++ b/src/Volo.Abp.MemoryDb/Volo/Abp/Domain/Repositories/MemoryDb/MemoryDbRepository.cs @@ -1,24 +1,16 @@ using System; using System.Collections.Generic; using System.Linq; +using System.Threading; +using System.Threading.Tasks; using Volo.Abp.Domain.Entities; using Volo.Abp.MemoryDb; namespace Volo.Abp.Domain.Repositories.MemoryDb { - public class MemoryDbRepository : MemoryDbRepository, IMemoryDbRepository + public class MemoryDbRepository : RepositoryBase, IMemoryDbRepository where TMemoryDbContext : MemoryDbContext - where TEntity : class, IEntity - { - public MemoryDbRepository(IMemoryDatabaseProvider databaseProvider) - : base(databaseProvider) - { - } - } - - public class MemoryDbRepository : QueryableRepositoryBase, IMemoryDbRepository - where TMemoryDbContext : MemoryDbContext - where TEntity : class, IEntity + where TEntity : class, IEntity { public virtual List Collection => Database.Collection(); @@ -33,35 +25,94 @@ namespace Volo.Abp.Domain.Repositories.MemoryDb public override TEntity Insert(TEntity entity, bool autoSave = false) { - SetIdIfNeeded(entity); Collection.Add(entity); return entity; } + public override TEntity Update(TEntity entity) + { + return entity; + } + + public override void Delete(TEntity entity) + { + Collection.Remove(entity); + } + + protected override IQueryable GetQueryable() + { + return ApplyDataFilters(Collection.AsQueryable()); + } + } + + public class MemoryDbRepository : MemoryDbRepository, IMemoryDbRepository + where TMemoryDbContext : MemoryDbContext + where TEntity : class, IEntity + { + public MemoryDbRepository(IMemoryDatabaseProvider databaseProvider) + : base(databaseProvider) + { + } + + public override TEntity Insert(TEntity entity, bool autoSave = false) + { + SetIdIfNeeded(entity); + return base.Insert(entity, autoSave); + } + private void SetIdIfNeeded(TEntity entity) { - if (typeof(TPrimaryKey) == typeof(int) || typeof(TPrimaryKey) == typeof(long) || typeof(TPrimaryKey) == typeof(Guid)) + if (typeof(TKey) == typeof(int) || typeof(TKey) == typeof(long) || typeof(TKey) == typeof(Guid)) { - if (entity.IsTransient()) + if (EntityHelper.IsTransient(entity)) { - entity.Id = Database.GenerateNextId(); + entity.Id = Database.GenerateNextId(); } } } - public override TEntity Update(TEntity entity) + public virtual TEntity Find(TKey id) { + return GetQueryable().FirstOrDefault(EntityHelper.CreateEqualityExpressionForId(id)); + } + + public virtual TEntity Get(TKey id) + { + var entity = Find(id); + + if (entity == null) + { + throw new EntityNotFoundException(typeof(TEntity), id); + } + return entity; } - - public override void Delete(TEntity entity) + + public virtual Task GetAsync(TKey id, CancellationToken cancellationToken = default) { - Collection.Remove(entity); + return Task.FromResult(Get(id)); } - protected override IQueryable GetQueryable() + public virtual Task FindAsync(TKey id, CancellationToken cancellationToken = default) { - return ApplyDataFilters(Collection.AsQueryable()); + return Task.FromResult(Find(id)); + } + + public virtual void Delete(TKey id) + { + var entity = Find(id); + if (entity == null) + { + return; + } + + Delete(entity); + } + + public virtual Task DeleteAsync(TKey id, CancellationToken cancellationToken = default) + { + Delete(id); + return Task.CompletedTask; } } } \ No newline at end of file diff --git a/src/Volo.Abp.MemoryDb/Volo/Abp/Domain/Repositories/MemoryDbCoreRepositoryExtensions.cs b/src/Volo.Abp.MemoryDb/Volo/Abp/Domain/Repositories/MemoryDbCoreRepositoryExtensions.cs index 71192d03ed..6f940ca146 100644 --- a/src/Volo.Abp.MemoryDb/Volo/Abp/Domain/Repositories/MemoryDbCoreRepositoryExtensions.cs +++ b/src/Volo.Abp.MemoryDb/Volo/Abp/Domain/Repositories/MemoryDbCoreRepositoryExtensions.cs @@ -7,25 +7,25 @@ namespace Volo.Abp.Domain.Repositories { public static class MemoryDbCoreRepositoryExtensions { - public static IMemoryDatabase GetDatabase(this IRepository repository) - where TEntity : class, IEntity + public static IMemoryDatabase GetDatabase(this IBasicRepository repository) + where TEntity : class, IEntity { return repository.ToMemoryDbRepository().Database; } - public static List GetCollection(this IRepository repository) - where TEntity : class, IEntity + public static List GetCollection(this IBasicRepository repository) + where TEntity : class, IEntity { return repository.ToMemoryDbRepository().Collection; } - public static IMemoryDbRepository ToMemoryDbRepository(this IRepository repository) - where TEntity : class, IEntity + public static IMemoryDbRepository ToMemoryDbRepository(this IBasicRepository repository) + where TEntity : class, IEntity { - var memoryDbRepository = repository as IMemoryDbRepository; + var memoryDbRepository = repository as IMemoryDbRepository; if (memoryDbRepository == null) { - throw new ArgumentException("Given repository does not implement " + typeof(IMemoryDbRepository).AssemblyQualifiedName, nameof(repository)); + throw new ArgumentException("Given repository does not implement " + typeof(IMemoryDbRepository).AssemblyQualifiedName, nameof(repository)); } return memoryDbRepository; diff --git a/src/Volo.Abp.MemoryDb/Volo/Abp/MemoryDb/DependencyInjection/MemoryDbRepositoryRegistrar.cs b/src/Volo.Abp.MemoryDb/Volo/Abp/MemoryDb/DependencyInjection/MemoryDbRepositoryRegistrar.cs index bf0d7dc011..fa238a780d 100644 --- a/src/Volo.Abp.MemoryDb/Volo/Abp/MemoryDb/DependencyInjection/MemoryDbRepositoryRegistrar.cs +++ b/src/Volo.Abp.MemoryDb/Volo/Abp/MemoryDb/DependencyInjection/MemoryDbRepositoryRegistrar.cs @@ -18,7 +18,7 @@ namespace Volo.Abp.MemoryDb.DependencyInjection return memoryDbContext.GetEntityTypes(); } - protected override Type GetRepositoryTypeForDefaultPk(Type dbContextType, Type entityType) + protected override Type GetRepositoryType(Type dbContextType, Type entityType) { return typeof(MemoryDbRepository<,>).MakeGenericType(dbContextType, entityType); } diff --git a/src/Volo.Abp.MongoDB/Volo/Abp/Domain/Repositories/MongoDB/IMongoDbRepository.cs b/src/Volo.Abp.MongoDB/Volo/Abp/Domain/Repositories/MongoDB/IMongoDbRepository.cs index 82ffb23f6b..31a39eb3a2 100644 --- a/src/Volo.Abp.MongoDB/Volo/Abp/Domain/Repositories/MongoDB/IMongoDbRepository.cs +++ b/src/Volo.Abp.MongoDB/Volo/Abp/Domain/Repositories/MongoDB/IMongoDbRepository.cs @@ -1,17 +1,10 @@ -using System; -using MongoDB.Driver; +using MongoDB.Driver; using Volo.Abp.Domain.Entities; namespace Volo.Abp.Domain.Repositories.MongoDB { - public interface IMongoDbRepository : IMongoDbRepository, IQueryableRepository - where TEntity : class, IEntity - { - - } - - public interface IMongoDbRepository : IQueryableRepository - where TEntity : class, IEntity + public interface IMongoDbRepository : IRepository + where TEntity : class, IEntity { IMongoDatabase Database { get; } @@ -19,4 +12,10 @@ namespace Volo.Abp.Domain.Repositories.MongoDB string CollectionName { get; } } + + public interface IMongoDbRepository : IMongoDbRepository, IRepository + where TEntity : class, IEntity + { + + } } diff --git a/src/Volo.Abp.MongoDB/Volo/Abp/Domain/Repositories/MongoDB/MongoDbRepository.cs b/src/Volo.Abp.MongoDB/Volo/Abp/Domain/Repositories/MongoDB/MongoDbRepository.cs index c18cb143b2..717f9a5771 100644 --- a/src/Volo.Abp.MongoDB/Volo/Abp/Domain/Repositories/MongoDB/MongoDbRepository.cs +++ b/src/Volo.Abp.MongoDB/Volo/Abp/Domain/Repositories/MongoDB/MongoDbRepository.cs @@ -1,5 +1,4 @@ using System; -using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading; @@ -10,19 +9,9 @@ using Volo.Abp.MongoDB; namespace Volo.Abp.Domain.Repositories.MongoDB { - public class MongoDbRepository : MongoDbRepository, IMongoDbRepository + public class MongoDbRepository : RepositoryBase, IMongoDbRepository where TMongoDbContext : AbpMongoDbContext - where TEntity : class, IEntity - { - public MongoDbRepository(IMongoDatabaseProvider databaseProvider) - : base(databaseProvider) - { - } - } - - public class MongoDbRepository : QueryableRepositoryBase, IMongoDbRepository - where TMongoDbContext : AbpMongoDbContext - where TEntity : class, IEntity + where TEntity : class, IEntity { public virtual string CollectionName => DatabaseProvider.DbContext.GetCollectionName(); @@ -37,25 +26,6 @@ namespace Volo.Abp.Domain.Repositories.MongoDB DatabaseProvider = databaseProvider; } - //TODO: Override other methods? - - public override async Task> GetListAsync(CancellationToken cancellationToken = new CancellationToken()) - { - return await (await Collection.FindAsync(Builders.Filter.Empty, cancellationToken: cancellationToken)).ToListAsync(cancellationToken); - } - - public override async Task GetAsync(TPrimaryKey id, CancellationToken cancellationToken = default) - { - var entity = await FindAsync(id, cancellationToken); - - if (entity == null) - { - throw new EntityNotFoundException(typeof(TEntity), id); - } - - return entity; - } - public override TEntity Insert(TEntity entity, bool autoSave = false) { Collection.InsertOne(entity); @@ -70,60 +40,109 @@ namespace Volo.Abp.Domain.Repositories.MongoDB public override TEntity Update(TEntity entity) { - var filter = Builders.Filter.Eq(e => e.Id, entity.Id); - Collection.ReplaceOne(filter, entity); + Collection.ReplaceOne(CreateEntityFilter(entity), entity); return entity; } public override async Task UpdateAsync(TEntity entity, CancellationToken cancellationToken = default) { - var filter = Builders.Filter.Eq(e => e.Id, entity.Id); - await Collection.ReplaceOneAsync(filter, entity, cancellationToken: cancellationToken); + await Collection.ReplaceOneAsync(CreateEntityFilter(entity), entity, cancellationToken: cancellationToken); return entity; } public override void Delete(TEntity entity) { - Delete(entity.Id); + Collection.DeleteOne(CreateEntityFilter(entity)); } - public override void Delete(TPrimaryKey id) + public override async Task DeleteAsync(TEntity entity, CancellationToken cancellationToken = default) { - var filter = Builders.Filter.Eq(e => e.Id, id); - Collection.DeleteOne(filter); + await Collection.DeleteOneAsync(CreateEntityFilter(entity), cancellationToken); } public override void Delete(Expression> predicate) { - var filter = Builders.Filter.Where(predicate); - Collection.DeleteOne(filter); + Collection.DeleteMany(Builders.Filter.Where(predicate)); } - public override Task DeleteAsync(TPrimaryKey id, CancellationToken cancellationToken = default) + public override async Task DeleteAsync(Expression> predicate, CancellationToken cancellationToken = default) { - var filter = Builders.Filter.Eq(e => e.Id, id); - return Collection.DeleteOneAsync(filter, cancellationToken: cancellationToken); + await Collection.DeleteManyAsync(Builders.Filter.Where(predicate), cancellationToken); } - public override Task DeleteAsync(TEntity entity, CancellationToken cancellationToken = default) + protected override IQueryable GetQueryable() { - return DeleteAsync(entity.Id, cancellationToken); + return Collection.AsQueryable(); } - public override Task DeleteAsync(Expression> predicate, CancellationToken cancellationToken = default) + protected virtual FilterDefinition CreateEntityFilter(TEntity entity) { - var filter = Builders.Filter.Where(predicate); - return Collection.DeleteOneAsync(filter, cancellationToken: cancellationToken); + throw new NotImplementedException("CreateEntityFilter is not implemented for MongoDb by default. It should be overrided and implemented by deriving classes!"); } + } - protected override IQueryable GetQueryable() + public class MongoDbRepository : MongoDbRepository, IMongoDbRepository + where TMongoDbContext : AbpMongoDbContext + where TEntity : class, IEntity + { + public MongoDbRepository(IMongoDatabaseProvider databaseProvider) + : base(databaseProvider) { - return Collection.AsQueryable(); + + } + + public virtual TEntity Get(TKey id) + { + var entity = Find(id); + + if (entity == null) + { + throw new EntityNotFoundException(typeof(TEntity), id); + } + + return entity; + } + + public virtual async Task GetAsync(TKey id, CancellationToken cancellationToken = default) + { + var entity = await FindAsync(id, cancellationToken); + + if (entity == null) + { + throw new EntityNotFoundException(typeof(TEntity), id); + } + + return entity; + } + + public virtual void Delete(TKey id) + { + Collection.DeleteOne(CreateEntityFilter(id)); + } + + public virtual Task DeleteAsync(TKey id, CancellationToken cancellationToken = default) + { + return Collection.DeleteOneAsync(CreateEntityFilter(id), cancellationToken); + } + + public virtual async Task FindAsync(TKey id, CancellationToken cancellationToken = default) + { + return await Collection.Find(CreateEntityFilter(id)).FirstOrDefaultAsync(cancellationToken); + } + + public virtual TEntity Find(TKey id) + { + return Collection.Find(CreateEntityFilter(id)).FirstOrDefault(); + } + + protected override FilterDefinition CreateEntityFilter(TEntity entity) + { + return Builders.Filter.Eq(e => e.Id, entity.Id); } - public override Task GetCountAsync(CancellationToken cancellationToken = default) + private static FilterDefinition CreateEntityFilter(TKey id) { - return Collection.CountAsync(Builders.Filter.Empty, cancellationToken: cancellationToken); + return Builders.Filter.Eq(e => e.Id, id); } } } \ No newline at end of file diff --git a/src/Volo.Abp.MongoDB/Volo/Abp/Domain/Repositories/MongoDbCoreRepositoryExtensions.cs b/src/Volo.Abp.MongoDB/Volo/Abp/Domain/Repositories/MongoDbCoreRepositoryExtensions.cs index b553637002..02a80cfa3a 100644 --- a/src/Volo.Abp.MongoDB/Volo/Abp/Domain/Repositories/MongoDbCoreRepositoryExtensions.cs +++ b/src/Volo.Abp.MongoDB/Volo/Abp/Domain/Repositories/MongoDbCoreRepositoryExtensions.cs @@ -7,31 +7,31 @@ namespace Volo.Abp.Domain.Repositories { public static class MongoDbCoreRepositoryExtensions { - public static IMongoDatabase GetDatabase(this IRepository repository) - where TEntity : class, IEntity + public static IMongoDatabase GetDatabase(this IBasicRepository repository) + where TEntity : class, IEntity { return repository.ToMongoDbRepository().Database; } - public static IMongoCollection GetCollection(this IRepository repository) - where TEntity : class, IEntity + public static IMongoCollection GetCollection(this IBasicRepository repository) + where TEntity : class, IEntity { return repository.ToMongoDbRepository().Collection; } - public static string GetCollectionName(this IRepository repository) - where TEntity : class, IEntity + public static string GetCollectionName(this IBasicRepository repository) + where TEntity : class, IEntity { return repository.ToMongoDbRepository().CollectionName; } - public static IMongoDbRepository ToMongoDbRepository(this IRepository repository) - where TEntity : class, IEntity + public static IMongoDbRepository ToMongoDbRepository(this IBasicRepository repository) + where TEntity : class, IEntity { - var mongoDbRepository = repository as IMongoDbRepository; + var mongoDbRepository = repository as IMongoDbRepository; if (mongoDbRepository == null) { - throw new ArgumentException("Given repository does not implement " + typeof(IMongoDbRepository).AssemblyQualifiedName, nameof(repository)); + throw new ArgumentException("Given repository does not implement " + typeof(IMongoDbRepository).AssemblyQualifiedName, nameof(repository)); } return mongoDbRepository; diff --git a/src/Volo.Abp.MongoDB/Volo/Abp/MongoDB/DependencyInjection/IMongoDbContextRegistrationOptionsBuilder.cs b/src/Volo.Abp.MongoDB/Volo/Abp/MongoDB/DependencyInjection/IMongoDbContextRegistrationOptionsBuilder.cs index 3e626b6558..6504639862 100644 --- a/src/Volo.Abp.MongoDB/Volo/Abp/MongoDB/DependencyInjection/IMongoDbContextRegistrationOptionsBuilder.cs +++ b/src/Volo.Abp.MongoDB/Volo/Abp/MongoDB/DependencyInjection/IMongoDbContextRegistrationOptionsBuilder.cs @@ -1,4 +1,3 @@ -using Volo.Abp.Data; using Volo.Abp.DependencyInjection; namespace Volo.Abp.MongoDB.DependencyInjection diff --git a/src/Volo.Abp.MongoDB/Volo/Abp/MongoDB/DependencyInjection/MongoDbRepositoryRegistrar.cs b/src/Volo.Abp.MongoDB/Volo/Abp/MongoDB/DependencyInjection/MongoDbRepositoryRegistrar.cs index 0ab8861ff5..362f2bdb31 100644 --- a/src/Volo.Abp.MongoDB/Volo/Abp/MongoDB/DependencyInjection/MongoDbRepositoryRegistrar.cs +++ b/src/Volo.Abp.MongoDB/Volo/Abp/MongoDB/DependencyInjection/MongoDbRepositoryRegistrar.cs @@ -19,9 +19,9 @@ namespace Volo.Abp.MongoDB.DependencyInjection return mongoDbContext.GetMappings().Select(m => m.EntityType); } - protected override Type GetRepositoryTypeForDefaultPk(Type dbContextType, Type entityType) + protected override Type GetRepositoryType(Type dbContextType, Type entityType) { - return typeof(MongoDbRepository<,>).MakeGenericType(dbContextType, entityType); + return typeof(MongoDbRepository<,,>).MakeGenericType(dbContextType, entityType); } protected override Type GetRepositoryType(Type dbContextType, Type entityType, Type primaryKeyType) diff --git a/src/Volo.Abp.MultiTenancy.Domain/Volo/Abp/MultiTenancy/ITenantRepository.cs b/src/Volo.Abp.MultiTenancy.Domain/Volo/Abp/MultiTenancy/ITenantRepository.cs index d8486c8ae6..b1c73774d9 100644 --- a/src/Volo.Abp.MultiTenancy.Domain/Volo/Abp/MultiTenancy/ITenantRepository.cs +++ b/src/Volo.Abp.MultiTenancy.Domain/Volo/Abp/MultiTenancy/ITenantRepository.cs @@ -4,7 +4,7 @@ using Volo.Abp.Domain.Repositories; namespace Volo.Abp.MultiTenancy { - public interface ITenantRepository : IRepository + public interface ITenantRepository : IBasicRepository { Task FindByNameIncludeDetailsAsync(string name); diff --git a/src/Volo.Abp.MultiTenancy.Domain/Volo/Abp/MultiTenancy/Tenant.cs b/src/Volo.Abp.MultiTenancy.Domain/Volo/Abp/MultiTenancy/Tenant.cs index 4a572526c5..4c6d4feac4 100644 --- a/src/Volo.Abp.MultiTenancy.Domain/Volo/Abp/MultiTenancy/Tenant.cs +++ b/src/Volo.Abp.MultiTenancy.Domain/Volo/Abp/MultiTenancy/Tenant.cs @@ -6,7 +6,7 @@ using Volo.Abp.Domain.Entities; namespace Volo.Abp.MultiTenancy { - public class Tenant : AggregateRoot + public class Tenant : AggregateRoot { public virtual string Name { get; protected set; } diff --git a/src/Volo.Abp.MultiTenancy.Domain/Volo/Abp/MultiTenancy/TenantConnectionString.cs b/src/Volo.Abp.MultiTenancy.Domain/Volo/Abp/MultiTenancy/TenantConnectionString.cs index 2d3c5235e1..c65163aaac 100644 --- a/src/Volo.Abp.MultiTenancy.Domain/Volo/Abp/MultiTenancy/TenantConnectionString.cs +++ b/src/Volo.Abp.MultiTenancy.Domain/Volo/Abp/MultiTenancy/TenantConnectionString.cs @@ -4,7 +4,7 @@ using Volo.Abp.Domain.Entities; namespace Volo.Abp.MultiTenancy { - public class TenantConnectionString : Entity //TODO: This should be a value object! + public class TenantConnectionString : Entity //TODO: PK should be TenantId + Name (so, inherit from Entity) { public virtual Guid TenantId { get; protected set; } diff --git a/src/Volo.Abp.MultiTenancy.EntityFrameworkCore/Volo/Abp/MultiTenancy/EfCoreTenantRepository.cs b/src/Volo.Abp.MultiTenancy.EntityFrameworkCore/Volo/Abp/MultiTenancy/EfCoreTenantRepository.cs index 66b6ed0fa3..6b52af0d1d 100644 --- a/src/Volo.Abp.MultiTenancy.EntityFrameworkCore/Volo/Abp/MultiTenancy/EfCoreTenantRepository.cs +++ b/src/Volo.Abp.MultiTenancy.EntityFrameworkCore/Volo/Abp/MultiTenancy/EfCoreTenantRepository.cs @@ -7,7 +7,7 @@ using Volo.Abp.MultiTenancy.EntityFrameworkCore; namespace Volo.Abp.MultiTenancy { - public class EfCoreTenantRepository : EfCoreRepository, ITenantRepository + public class EfCoreTenantRepository : EfCoreRepository, ITenantRepository { public EfCoreTenantRepository(IDbContextProvider dbContextProvider) : base(dbContextProvider) diff --git a/src/Volo.Abp.Threading/Volo/Abp/Threading/CancellationTokenProviderExtensions.cs b/src/Volo.Abp.Threading/Volo/Abp/Threading/CancellationTokenProviderExtensions.cs index 0f84c725c5..b1ad755db2 100644 --- a/src/Volo.Abp.Threading/Volo/Abp/Threading/CancellationTokenProviderExtensions.cs +++ b/src/Volo.Abp.Threading/Volo/Abp/Threading/CancellationTokenProviderExtensions.cs @@ -4,7 +4,7 @@ namespace Volo.Abp.Threading { public static class CancellationTokenProviderExtensions { - public static CancellationToken FallbackToProvider(this ICancellationTokenProvider provider, CancellationToken prefferedValue) + public static CancellationToken FallbackToProvider(this ICancellationTokenProvider provider, CancellationToken prefferedValue = default) { return prefferedValue == default ? provider.Token : prefferedValue; } diff --git a/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/PersonAppService_Tests.cs b/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/PersonAppService_Tests.cs index 445e226de4..031a6d6c89 100644 --- a/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/PersonAppService_Tests.cs +++ b/test/Volo.Abp.AspNetCore.Mvc.Tests/Volo/Abp/AspNetCore/Mvc/PersonAppService_Tests.cs @@ -3,7 +3,6 @@ using Shouldly; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Volo.Abp.Application.Dtos; -using Volo.Abp.TestApp.Application; using Volo.Abp.TestApp.Domain; using Xunit; using Volo.Abp.Domain.Repositories; @@ -21,13 +20,13 @@ namespace Volo.Abp.AspNetCore.Mvc public class PersonAppService_Tests : AspNetCoreMvcTestBase { - private readonly IQueryableRepository _personRepository; + private readonly IRepository _personRepository; private readonly IJsonSerializer _jsonSerializer; private readonly IObjectMapper _objectMapper; public PersonAppService_Tests() { - _personRepository = ServiceProvider.GetRequiredService>(); + _personRepository = ServiceProvider.GetRequiredService>(); _jsonSerializer = ServiceProvider.GetRequiredService(); _objectMapper = ServiceProvider.GetRequiredService(); } @@ -42,7 +41,7 @@ namespace Volo.Abp.AspNetCore.Mvc [Fact] public async Task Get_Test() { - var firstPerson = _personRepository.GetList().First(); + var firstPerson = _personRepository.First(); var result = await GetResponseAsObjectAsync($"/api/app/people/{firstPerson.Id}"); result.Name.ShouldBe(firstPerson.Name); @@ -51,7 +50,7 @@ namespace Volo.Abp.AspNetCore.Mvc [Fact] public async Task Delete_Test() { - var firstPerson = _personRepository.GetList().First(); + var firstPerson = _personRepository.First(); await Client.DeleteAsync($"/api/app/people/{firstPerson.Id}"); @@ -89,7 +88,7 @@ namespace Volo.Abp.AspNetCore.Mvc { //Arrange - var firstPerson = _personRepository.GetList().First(); + var firstPerson = _personRepository.First(); var firstPersonAge = firstPerson.Age; //Persist to a variable since we are using in-memory database which shares same entity. var updateDto = _objectMapper.Map(firstPerson); updateDto.Age = updateDto.Age + 1; @@ -123,7 +122,7 @@ namespace Volo.Abp.AspNetCore.Mvc { //Arrange - var personToAddNewPhone = _personRepository.GetList().First(); + var personToAddNewPhone = _personRepository.First(); var phoneNumberToAdd = RandomHelper.GetRandom(1000000, 9000000).ToString(); //Act @@ -152,7 +151,7 @@ namespace Volo.Abp.AspNetCore.Mvc [Fact] public async Task GetPhones_Test() { - var douglas = _personRepository.GetList().First(p => p.Name == "Douglas"); + var douglas = _personRepository.First(p => p.Name == "Douglas"); var result = await GetResponseAsObjectAsync>($"/api/app/people/{douglas.Id}/phones"); result.Items.Count.ShouldBe(douglas.Phones.Count); @@ -161,13 +160,13 @@ namespace Volo.Abp.AspNetCore.Mvc [Fact] public async Task DeletePhone_Test() { - var douglas = _personRepository.GetList().First(p => p.Name == "Douglas"); + var douglas = _personRepository.First(p => p.Name == "Douglas"); var firstPhone = douglas.Phones.First(); - await Client.DeleteAsync($"/api/app/people/{douglas.Id}/phones/{firstPhone.Id}"); + await Client.DeleteAsync($"/api/app/people/{douglas.Id}/phones?number={firstPhone.Number}"); - douglas = _personRepository.GetList().First(p => p.Name == "Douglas"); - douglas.Phones.Any(p => p.Id == firstPhone.Id).ShouldBeFalse(); + douglas = _personRepository.First(p => p.Name == "Douglas"); + douglas.Phones.Any(p => p.Number == firstPhone.Number).ShouldBeFalse(); } } } \ No newline at end of file diff --git a/test/Volo.Abp.AutoMapper.Tests/Volo/Abp/AutoMapper/SampleClasses/MyEntity.cs b/test/Volo.Abp.AutoMapper.Tests/Volo/Abp/AutoMapper/SampleClasses/MyEntity.cs index 0a0b2f6bf4..8f24cb0966 100644 --- a/test/Volo.Abp.AutoMapper.Tests/Volo/Abp/AutoMapper/SampleClasses/MyEntity.cs +++ b/test/Volo.Abp.AutoMapper.Tests/Volo/Abp/AutoMapper/SampleClasses/MyEntity.cs @@ -1,8 +1,9 @@ -using Volo.Abp.Domain.Entities; +using System; +using Volo.Abp.Domain.Entities; namespace Volo.Abp.AutoMapper.SampleClasses { - public class MyEntity : Entity + public class MyEntity : Entity { public int Number { get; set; } } diff --git a/test/Volo.Abp.AutoMapper.Tests/Volo/Abp/AutoMapper/SampleClasses/MyEntityDto.cs b/test/Volo.Abp.AutoMapper.Tests/Volo/Abp/AutoMapper/SampleClasses/MyEntityDto.cs index 61e3e9b3bd..1d34d6858a 100644 --- a/test/Volo.Abp.AutoMapper.Tests/Volo/Abp/AutoMapper/SampleClasses/MyEntityDto.cs +++ b/test/Volo.Abp.AutoMapper.Tests/Volo/Abp/AutoMapper/SampleClasses/MyEntityDto.cs @@ -1,9 +1,10 @@ -using Volo.Abp.Application.Dtos; +using System; +using Volo.Abp.Application.Dtos; namespace Volo.Abp.AutoMapper.SampleClasses { [AutoMap(typeof(MyEntity))] - public class MyEntityDto : EntityDto + public class MyEntityDto : EntityDto { public int Number { get; set; } } diff --git a/test/Volo.Abp.AutoMapper.Tests/Volo/Abp/AutoMapper/SampleClasses/MyEntityDto2.cs b/test/Volo.Abp.AutoMapper.Tests/Volo/Abp/AutoMapper/SampleClasses/MyEntityDto2.cs index b01af5a7f9..ba67552ca0 100644 --- a/test/Volo.Abp.AutoMapper.Tests/Volo/Abp/AutoMapper/SampleClasses/MyEntityDto2.cs +++ b/test/Volo.Abp.AutoMapper.Tests/Volo/Abp/AutoMapper/SampleClasses/MyEntityDto2.cs @@ -1,8 +1,9 @@ +using System; using Volo.Abp.Application.Dtos; namespace Volo.Abp.AutoMapper.SampleClasses { - public class MyEntityDto2 : EntityDto + public class MyEntityDto2 : EntityDto { public int Number { get; set; } } diff --git a/test/Volo.Abp.AutoMapper.Tests/Volo/Abp/AutoMapper/SampleClasses/MyNotMappedDto.cs b/test/Volo.Abp.AutoMapper.Tests/Volo/Abp/AutoMapper/SampleClasses/MyNotMappedDto.cs index a69e50d819..096da7799c 100644 --- a/test/Volo.Abp.AutoMapper.Tests/Volo/Abp/AutoMapper/SampleClasses/MyNotMappedDto.cs +++ b/test/Volo.Abp.AutoMapper.Tests/Volo/Abp/AutoMapper/SampleClasses/MyNotMappedDto.cs @@ -1,8 +1,9 @@ -using Volo.Abp.Application.Dtos; +using System; +using Volo.Abp.Application.Dtos; namespace Volo.Abp.AutoMapper.SampleClasses { - public class MyNotMappedDto : EntityDto + public class MyNotMappedDto : EntityDto { public int Number { get; set; } } diff --git a/test/Volo.Abp.Ddd.Tests/Volo.Abp.Ddd.Tests.csproj b/test/Volo.Abp.Ddd.Tests/Volo.Abp.Ddd.Tests.csproj index e3fd3e19f6..faf42e147e 100644 --- a/test/Volo.Abp.Ddd.Tests/Volo.Abp.Ddd.Tests.csproj +++ b/test/Volo.Abp.Ddd.Tests/Volo.Abp.Ddd.Tests.csproj @@ -2,6 +2,7 @@ netcoreapp2.0 + latest Volo.Abp.Ddd.Tests Volo.Abp.Ddd.Tests true diff --git a/test/Volo.Abp.Ddd.Tests/Volo.Abp.Ddd.Tests.csproj.DotSettings b/test/Volo.Abp.Ddd.Tests/Volo.Abp.Ddd.Tests.csproj.DotSettings new file mode 100644 index 0000000000..58ad6c8854 --- /dev/null +++ b/test/Volo.Abp.Ddd.Tests/Volo.Abp.Ddd.Tests.csproj.DotSettings @@ -0,0 +1,2 @@ + + CSharp71 \ No newline at end of file diff --git a/test/Volo.Abp.Ddd.Tests/Volo/Abp/Domain/Repositories/RepositoryRegistration_Tests.cs b/test/Volo.Abp.Ddd.Tests/Volo/Abp/Domain/Repositories/RepositoryRegistration_Tests.cs index fbbbc0c77c..9fc5e2cff8 100644 --- a/test/Volo.Abp.Ddd.Tests/Volo/Abp/Domain/Repositories/RepositoryRegistration_Tests.cs +++ b/test/Volo.Abp.Ddd.Tests/Volo/Abp/Domain/Repositories/RepositoryRegistration_Tests.cs @@ -1,7 +1,8 @@ using System; using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; -using Volo.Abp.Data; using Volo.Abp.DependencyInjection; using Volo.Abp.Domain.Entities; using Xunit; @@ -26,9 +27,11 @@ namespace Volo.Abp.Domain.Repositories //Assert - services.ShouldContainTransient(typeof(IRepository), typeof(MyTestDefaultRepository)); - services.ShouldContainTransient(typeof(IRepository), typeof(MyTestDefaultRepository)); - services.ShouldNotContainService(typeof(IRepository)); + services.ShouldContainTransient(typeof(IBasicRepository), typeof(MyTestDefaultRepository)); + services.ShouldContainTransient(typeof(IBasicRepository), typeof(MyTestDefaultRepository)); + services.ShouldContainTransient(typeof(IBasicRepository), typeof(MyTestDefaultRepository)); + + services.ShouldNotContainService(typeof(IBasicRepository)); } [Fact] @@ -47,9 +50,11 @@ namespace Volo.Abp.Domain.Repositories //Assert - services.ShouldContainTransient(typeof(IRepository), typeof(MyTestDefaultRepository)); - services.ShouldContainTransient(typeof(IRepository), typeof(MyTestDefaultRepository)); - services.ShouldContainTransient(typeof(IRepository), typeof(MyTestDefaultRepository)); + services.ShouldContainTransient(typeof(IBasicRepository), typeof(MyTestDefaultRepository)); + services.ShouldContainTransient(typeof(IBasicRepository), typeof(MyTestDefaultRepository)); + services.ShouldContainTransient(typeof(IBasicRepository), typeof(MyTestDefaultRepository)); + services.ShouldContainTransient(typeof(IBasicRepository), typeof(MyTestDefaultRepository)); + services.ShouldContainTransient(typeof(IBasicRepository), typeof(MyTestDefaultRepository)); } [Fact] @@ -62,7 +67,7 @@ namespace Volo.Abp.Domain.Repositories var options = new TestDbContextRegistrationOptions(typeof(MyFakeDbContext)); options .AddDefaultRepositories(true) - .AddCustomRepository(); + .AddRepository(); //Act @@ -70,9 +75,10 @@ namespace Volo.Abp.Domain.Repositories //Assert - services.ShouldContainTransient(typeof(IRepository), typeof(MyTestAggregateRootWithDefaultPkCustomRepository)); - services.ShouldContainTransient(typeof(IRepository), typeof(MyTestAggregateRootWithDefaultPkCustomRepository)); - services.ShouldContainTransient(typeof(IRepository), typeof(MyTestDefaultRepository)); + services.ShouldContainTransient(typeof(IBasicRepository), typeof(MyTestDefaultRepository)); + services.ShouldContainTransient(typeof(IBasicRepository), typeof(MyTestAggregateRootWithDefaultPkCustomRepository)); + services.ShouldContainTransient(typeof(IBasicRepository), typeof(MyTestAggregateRootWithDefaultPkCustomRepository)); + services.ShouldContainTransient(typeof(IBasicRepository), typeof(MyTestDefaultRepository)); } [Fact] @@ -93,14 +99,15 @@ namespace Volo.Abp.Domain.Repositories //Assert - services.ShouldContainTransient(typeof(IRepository), typeof(MyTestCustomBaseRepository)); - services.ShouldContainTransient(typeof(IRepository), typeof(MyTestCustomBaseRepository)); - services.ShouldContainTransient(typeof(IRepository), typeof(MyTestCustomBaseRepository)); + services.ShouldContainTransient(typeof(IBasicRepository), typeof(MyTestCustomBaseRepository)); + services.ShouldContainTransient(typeof(IBasicRepository), typeof(MyTestCustomBaseRepository)); + services.ShouldContainTransient(typeof(IBasicRepository), typeof(MyTestCustomBaseRepository)); + services.ShouldContainTransient(typeof(IBasicRepository), typeof(MyTestCustomBaseRepository)); } public class MyTestRepositoryRegistrar : RepositoryRegistrarBase { - public MyTestRepositoryRegistrar(CommonDbContextRegistrationOptions options) + public MyTestRepositoryRegistrar(CommonDbContextRegistrationOptions options) : base(options) { } @@ -109,12 +116,13 @@ namespace Volo.Abp.Domain.Repositories { return new[] { - typeof(MyTestEntityWithCustomPk), - typeof(MyTestAggregateRootWithDefaultPk) + typeof(MyTestEntityWithInt32Pk), + typeof(MyTestAggregateRootWithGuidPk), + typeof(MyTestAggregateRootWithoutPk) }; } - protected override Type GetRepositoryTypeForDefaultPk(Type dbContextType, Type entityType) + protected override Type GetRepositoryType(Type dbContextType, Type entityType) { return typeof(MyTestDefaultRepository<>).MakeGenericType(entityType); } @@ -127,76 +135,94 @@ namespace Volo.Abp.Domain.Repositories public class MyFakeDbContext { } - public class MyTestAggregateRootWithDefaultPk : AggregateRoot + public class MyTestAggregateRootWithGuidPk : AggregateRoot { - + } - public class MyTestEntityWithCustomPk : Entity + public class MyTestEntityWithInt32Pk : Entity { } - public class MyTestDefaultRepository : MyTestDefaultRepository, IRepository - where TEntity : class, IEntity + public class MyTestAggregateRootWithoutPk : AggregateRoot { - + public string MyId { get; set; } } - public class MyTestDefaultRepository : RepositoryBase - where TEntity : class, IEntity + public class MyTestDefaultRepository : BasicRepositoryBase + where TEntity : class, IEntity { - public override TEntity Find(TPrimaryKey id) + public override TEntity Insert(TEntity entity, bool autoSave = false) { throw new NotImplementedException(); } - public override TEntity Insert(TEntity entity, bool autoSave = false) + public override TEntity Update(TEntity entity) { throw new NotImplementedException(); } - public override TEntity Update(TEntity entity) + public override void Delete(TEntity entity) { throw new NotImplementedException(); } + } - public override void Delete(TEntity entity) + public class MyTestDefaultRepository : MyTestDefaultRepository, IBasicRepository + where TEntity : class, IEntity + { + public TEntity Get(TKey id) + { + throw new NotImplementedException(); + } + + public Task GetAsync(TKey id, CancellationToken cancellationToken = default) + { + throw new NotImplementedException(); + } + + public TEntity Find(TKey id) + { + throw new NotImplementedException(); + } + + public Task FindAsync(TKey id, CancellationToken cancellationToken = default) { throw new NotImplementedException(); } - public override long GetCount() + public void Delete(TKey id) { throw new NotImplementedException(); } - public override List GetList() + public Task DeleteAsync(TKey id, CancellationToken cancellationToken = default) { throw new NotImplementedException(); } } - public class MyTestAggregateRootWithDefaultPkCustomRepository : MyTestDefaultRepository + public class MyTestAggregateRootWithDefaultPkCustomRepository : MyTestDefaultRepository { } - public class MyTestCustomBaseRepository : MyTestCustomBaseRepository, IRepository - where TEntity : class, IEntity + public class MyTestCustomBaseRepository : MyTestDefaultRepository + where TEntity : class, IEntity { } - public class MyTestCustomBaseRepository : MyTestDefaultRepository - where TEntity : class, IEntity + public class MyTestCustomBaseRepository : MyTestDefaultRepository + where TEntity : class, IEntity { } public class TestDbContextRegistrationOptions : CommonDbContextRegistrationOptions { - public TestDbContextRegistrationOptions(Type originalDbContextType) + public TestDbContextRegistrationOptions(Type originalDbContextType) : base(originalDbContextType) { } diff --git a/test/Volo.Abp.EntityFrameworkCore.Tests.SecondContext/Volo/Abp/EntityFrameworkCore/TestApp/SecondContext/BookInSecondDbContext.cs b/test/Volo.Abp.EntityFrameworkCore.Tests.SecondContext/Volo/Abp/EntityFrameworkCore/TestApp/SecondContext/BookInSecondDbContext.cs index 61bc73b5ec..0e22533c11 100644 --- a/test/Volo.Abp.EntityFrameworkCore.Tests.SecondContext/Volo/Abp/EntityFrameworkCore/TestApp/SecondContext/BookInSecondDbContext.cs +++ b/test/Volo.Abp.EntityFrameworkCore.Tests.SecondContext/Volo/Abp/EntityFrameworkCore/TestApp/SecondContext/BookInSecondDbContext.cs @@ -1,8 +1,9 @@ -using Volo.Abp.Domain.Entities; +using System; +using Volo.Abp.Domain.Entities; namespace Volo.Abp.EntityFrameworkCore.TestApp.SecondContext { - public class BookInSecondDbContext : AggregateRoot + public class BookInSecondDbContext : AggregateRoot { public string Name { get; set; } } diff --git a/test/Volo.Abp.EntityFrameworkCore.Tests.SecondContext/Volo/Abp/EntityFrameworkCore/TestApp/SecondContext/PhoneInSecondDbContext.cs b/test/Volo.Abp.EntityFrameworkCore.Tests.SecondContext/Volo/Abp/EntityFrameworkCore/TestApp/SecondContext/PhoneInSecondDbContext.cs index 7c4c317c00..568c8b6ba2 100644 --- a/test/Volo.Abp.EntityFrameworkCore.Tests.SecondContext/Volo/Abp/EntityFrameworkCore/TestApp/SecondContext/PhoneInSecondDbContext.cs +++ b/test/Volo.Abp.EntityFrameworkCore.Tests.SecondContext/Volo/Abp/EntityFrameworkCore/TestApp/SecondContext/PhoneInSecondDbContext.cs @@ -1,11 +1,14 @@ -using System.ComponentModel.DataAnnotations.Schema; +using System; +using System.ComponentModel.DataAnnotations.Schema; using Volo.Abp.Domain.Entities; namespace Volo.Abp.EntityFrameworkCore.TestApp.SecondContext { [Table("AppPhones")] - public class PhoneInSecondDbContext : AggregateRoot + public class PhoneInSecondDbContext : AggregateRoot { + public virtual Guid PersonId { get; set; } + public virtual string Number { get; set; } } } \ No newline at end of file diff --git a/test/Volo.Abp.EntityFrameworkCore.Tests.SecondContext/Volo/Abp/EntityFrameworkCore/TestApp/SecondContext/SecondContextTestDataBuilder.cs b/test/Volo.Abp.EntityFrameworkCore.Tests.SecondContext/Volo/Abp/EntityFrameworkCore/TestApp/SecondContext/SecondContextTestDataBuilder.cs index 1beb893d17..59ddc2acdf 100644 --- a/test/Volo.Abp.EntityFrameworkCore.Tests.SecondContext/Volo/Abp/EntityFrameworkCore/TestApp/SecondContext/SecondContextTestDataBuilder.cs +++ b/test/Volo.Abp.EntityFrameworkCore.Tests.SecondContext/Volo/Abp/EntityFrameworkCore/TestApp/SecondContext/SecondContextTestDataBuilder.cs @@ -1,4 +1,5 @@ -using Volo.Abp.DependencyInjection; +using System; +using Volo.Abp.DependencyInjection; using Volo.Abp.Domain.Repositories; using Volo.Abp.Guids; @@ -6,10 +7,10 @@ namespace Volo.Abp.EntityFrameworkCore.TestApp.SecondContext { public class SecondContextTestDataBuilder : ITransientDependency { - private readonly IRepository _bookRepository; + private readonly IBasicRepository _bookRepository; private readonly IGuidGenerator _guidGenerator; - public SecondContextTestDataBuilder(IRepository bookRepository, IGuidGenerator guidGenerator) + public SecondContextTestDataBuilder(IBasicRepository bookRepository, IGuidGenerator guidGenerator) { _bookRepository = bookRepository; _guidGenerator = guidGenerator; diff --git a/test/Volo.Abp.EntityFrameworkCore.Tests.SecondContext/Volo/Abp/EntityFrameworkCore/TestApp/SecondContext/SecondDbContext.cs b/test/Volo.Abp.EntityFrameworkCore.Tests.SecondContext/Volo/Abp/EntityFrameworkCore/TestApp/SecondContext/SecondDbContext.cs index d2b54bc699..f07ffbc5a3 100644 --- a/test/Volo.Abp.EntityFrameworkCore.Tests.SecondContext/Volo/Abp/EntityFrameworkCore/TestApp/SecondContext/SecondDbContext.cs +++ b/test/Volo.Abp.EntityFrameworkCore.Tests.SecondContext/Volo/Abp/EntityFrameworkCore/TestApp/SecondContext/SecondDbContext.cs @@ -12,5 +12,15 @@ namespace Volo.Abp.EntityFrameworkCore.TestApp.SecondContext : base(options) { } + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + base.OnModelCreating(modelBuilder); + + modelBuilder.Entity(b => + { + b.HasKey(p => new { p.PersonId, p.Number }); + }); + } } } \ No newline at end of file diff --git a/test/Volo.Abp.EntityFrameworkCore.Tests.SecondContext/Volo/Abp/EntityFrameworkCore/TestApp/ThirdDbContext/ThirdDbContextDummyEntity.cs b/test/Volo.Abp.EntityFrameworkCore.Tests.SecondContext/Volo/Abp/EntityFrameworkCore/TestApp/ThirdDbContext/ThirdDbContextDummyEntity.cs index f88dfc2cb8..bcb1cf65b7 100644 --- a/test/Volo.Abp.EntityFrameworkCore.Tests.SecondContext/Volo/Abp/EntityFrameworkCore/TestApp/ThirdDbContext/ThirdDbContextDummyEntity.cs +++ b/test/Volo.Abp.EntityFrameworkCore.Tests.SecondContext/Volo/Abp/EntityFrameworkCore/TestApp/ThirdDbContext/ThirdDbContextDummyEntity.cs @@ -1,8 +1,9 @@ -using Volo.Abp.Domain.Entities; +using System; +using Volo.Abp.Domain.Entities; namespace Volo.Abp.EntityFrameworkCore.TestApp.ThirdDbContext { - public class ThirdDbContextDummyEntity : AggregateRoot + public class ThirdDbContextDummyEntity : AggregateRoot { public string Value { get; set; } } diff --git a/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/AbpEntityFrameworkCoreTestModule.cs b/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/AbpEntityFrameworkCoreTestModule.cs index b6b77d26f8..9496844b0b 100644 --- a/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/AbpEntityFrameworkCoreTestModule.cs +++ b/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/AbpEntityFrameworkCoreTestModule.cs @@ -22,7 +22,7 @@ namespace Volo.Abp.EntityFrameworkCore services.AddAbpDbContext(options => { - options.AddDefaultRepositories(); + options.AddDefaultRepositories(true); options.ReplaceDbContext(); }); diff --git a/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DataFiltering/MultiTenant_Filter_Tests.cs b/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DataFiltering/MultiTenant_Filter_Tests.cs index ab9dda2e72..976e26ee40 100644 --- a/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DataFiltering/MultiTenant_Filter_Tests.cs +++ b/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DataFiltering/MultiTenant_Filter_Tests.cs @@ -14,15 +14,15 @@ using Xunit; namespace Volo.Abp.EntityFrameworkCore.DataFiltering { - public class MultiTenant_Filter_Tests : EntityFrameworkCoreTestBase + public class MultiTenant_Filter_Tests : EntityFrameworkCoreTestBase //TODO: This class is same of Volo.Abp.MemoryDb.DataFilters.MemoryDb_MultiTenant_Filter_Tests. Can we share source code? { private ICurrentTenant _fakeCurrentTenant; - private readonly IRepository _personRepository; + private readonly IRepository _personRepository; private readonly IDataFilter _multiTenantFilter; public MultiTenant_Filter_Tests() { - _personRepository = GetRequiredService>(); + _personRepository = GetRequiredService>(); _multiTenantFilter = GetRequiredService>(); } @@ -33,48 +33,54 @@ namespace Volo.Abp.EntityFrameworkCore.DataFiltering } [Fact] - public async Task Should_Get_Person_For_Current_Tenant() + public void Should_Get_Person_For_Current_Tenant() { - //TenantId = null + WithUnitOfWork(() => + { + //TenantId = null - _fakeCurrentTenant.Id.Returns((Guid?)null); + _fakeCurrentTenant.Id.Returns((Guid?)null); - var people = await _personRepository.GetListAsync(); - people.Count.ShouldBe(1); - people.Any(p => p.Name == "Douglas").ShouldBeTrue(); + var people = _personRepository.ToList(); + people.Count.ShouldBe(1); + people.Any(p => p.Name == "Douglas").ShouldBeTrue(); - //TenantId = TestDataBuilder.TenantId1 + //TenantId = TestDataBuilder.TenantId1 - _fakeCurrentTenant.Id.Returns(TestDataBuilder.TenantId1); + _fakeCurrentTenant.Id.Returns(TestDataBuilder.TenantId1); - people = await _personRepository.GetListAsync(); - people.Count.ShouldBe(2); - people.Any(p => p.Name == TestDataBuilder.TenantId1 + "-Person1").ShouldBeTrue(); - people.Any(p => p.Name == TestDataBuilder.TenantId1 + "-Person2").ShouldBeTrue(); + people = _personRepository.ToList(); + people.Count.ShouldBe(2); + people.Any(p => p.Name == TestDataBuilder.TenantId1 + "-Person1").ShouldBeTrue(); + people.Any(p => p.Name == TestDataBuilder.TenantId1 + "-Person2").ShouldBeTrue(); - //TenantId = TestDataBuilder.TenantId2 + //TenantId = TestDataBuilder.TenantId2 - _fakeCurrentTenant.Id.Returns(TestDataBuilder.TenantId2); + _fakeCurrentTenant.Id.Returns(TestDataBuilder.TenantId2); - people = await _personRepository.GetListAsync(); - people.Count.ShouldBe(0); + people = _personRepository.ToList(); + people.Count.ShouldBe(0); + }); } [Fact] - public async Task Should_Get_All_People_When_MultiTenant_Filter_Is_Disabled() + public void Should_Get_All_People_When_MultiTenant_Filter_Is_Disabled() { - List people; - - using (_multiTenantFilter.Disable()) + WithUnitOfWork(() => { - //Filter disabled manually - people = await _personRepository.GetListAsync(); - people.Count.ShouldBe(3); - } + List people; + + using (_multiTenantFilter.Disable()) + { + //Filter disabled manually + people = _personRepository.ToList(); + people.Count.ShouldBe(3); + } - //Filter re-enabled automatically - people = await _personRepository.GetListAsync(); - people.Count.ShouldBe(1); + //Filter re-enabled automatically + people = _personRepository.ToList(); + people.Count.ShouldBe(1); + }); } } } diff --git a/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DataFiltering/SoftDelete_Filter_Tests.cs b/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DataFiltering/SoftDelete_Filter_Tests.cs index ba28f82b5c..c17977e463 100644 --- a/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DataFiltering/SoftDelete_Filter_Tests.cs +++ b/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DataFiltering/SoftDelete_Filter_Tests.cs @@ -1,4 +1,5 @@ -using System.Linq; +using System; +using System.Linq; using Shouldly; using Volo.Abp.Data; using Volo.Abp.Domain.Repositories; @@ -9,56 +10,62 @@ namespace Volo.Abp.EntityFrameworkCore.DataFiltering { public class SoftDelete_Filter_Tests : EntityFrameworkCoreTestBase { - private readonly IRepository _personRepository; + private readonly IRepository _personRepository; private readonly IDataFilter _dataFilter; public SoftDelete_Filter_Tests() { - _personRepository = GetRequiredService>(); + _personRepository = GetRequiredService>(); _dataFilter = GetRequiredService(); } [Fact] public void Should_Not_Get_Deleted_Entities_By_Default() { - var people = _personRepository.GetList(); - people.Count.ShouldBe(1); - people.Any(p => p.Name == "Douglas").ShouldBeTrue(); + WithUnitOfWork(() => + { + var people = _personRepository.ToList(); + people.Count.ShouldBe(1); + people.Any(p => p.Name == "Douglas").ShouldBeTrue(); + }); } [Fact] public void Should_Get_Deleted_Entities_When_Filter_Is_Disabled() { - //Soft delete is enabled by default - var people = _personRepository.GetList(); - people.Any(p => !p.IsDeleted).ShouldBeTrue(); - people.Any(p => p.IsDeleted).ShouldBeFalse(); - - using (_dataFilter.Disable()) + WithUnitOfWork(() => { - //Soft delete is disabled - people = _personRepository.GetList(); + //Soft delete is enabled by default + var people = _personRepository.ToList(); people.Any(p => !p.IsDeleted).ShouldBeTrue(); - people.Any(p => p.IsDeleted).ShouldBeTrue(); + people.Any(p => p.IsDeleted).ShouldBeFalse(); - using (_dataFilter.Enable()) + using (_dataFilter.Disable()) { - //Soft delete is enabled again - people = _personRepository.GetList(); + //Soft delete is disabled + people = _personRepository.ToList(); + people.Any(p => !p.IsDeleted).ShouldBeTrue(); + people.Any(p => p.IsDeleted).ShouldBeTrue(); + + using (_dataFilter.Enable()) + { + //Soft delete is enabled again + people = _personRepository.ToList(); + people.Any(p => !p.IsDeleted).ShouldBeTrue(); + people.Any(p => p.IsDeleted).ShouldBeFalse(); + } + + //Soft delete is disabled (restored previous state) + people = _personRepository.ToList(); people.Any(p => !p.IsDeleted).ShouldBeTrue(); - people.Any(p => p.IsDeleted).ShouldBeFalse(); + people.Any(p => p.IsDeleted).ShouldBeTrue(); } - //Soft delete is disabled (restored previous state) - people = _personRepository.GetList(); + //Soft delete is enabled (restored previous state) + people = _personRepository.ToList(); people.Any(p => !p.IsDeleted).ShouldBeTrue(); - people.Any(p => p.IsDeleted).ShouldBeTrue(); - } - - //Soft delete is enabled (restored previous state) - people = _personRepository.GetList(); - people.Any(p => !p.IsDeleted).ShouldBeTrue(); - people.Any(p => p.IsDeleted).ShouldBeFalse(); + people.Any(p => p.IsDeleted).ShouldBeFalse(); + }); } } } diff --git a/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DbContext_Replace_Tests.cs b/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DbContext_Replace_Tests.cs index a86797feed..8ada582fa6 100644 --- a/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DbContext_Replace_Tests.cs +++ b/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/DbContext_Replace_Tests.cs @@ -1,4 +1,5 @@ -using Microsoft.Extensions.DependencyInjection; +using System; +using Microsoft.Extensions.DependencyInjection; using Shouldly; using Volo.Abp.Domain.Repositories; using Volo.Abp.EntityFrameworkCore.TestApp.ThirdDbContext; @@ -9,11 +10,11 @@ namespace Volo.Abp.EntityFrameworkCore { public class DbContext_Replace_Tests : EntityFrameworkCoreTestBase { - private readonly IRepository _dummyRepository; + private readonly IBasicRepository _dummyRepository; public DbContext_Replace_Tests() { - _dummyRepository = ServiceProvider.GetRequiredService>(); + _dummyRepository = ServiceProvider.GetRequiredService>(); } [Fact] diff --git a/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/Repositories/Basic_Repository_Tests.cs b/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/Repositories/Basic_Repository_Tests.cs deleted file mode 100644 index 3c2edb33f9..0000000000 --- a/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/Repositories/Basic_Repository_Tests.cs +++ /dev/null @@ -1,55 +0,0 @@ -using System; -using System.Linq; -using System.Threading.Tasks; -using Microsoft.Extensions.DependencyInjection; -using Shouldly; -using Volo.Abp.Domain.Repositories; -using Volo.Abp.EntityFrameworkCore.TestApp.SecondContext; -using Volo.Abp.TestApp.Domain; -using Xunit; - -namespace Volo.Abp.EntityFrameworkCore.Repositories -{ - public class Basic_Repository_Tests : EntityFrameworkCoreTestBase - { - private readonly IRepository _personRepository; - private readonly IRepository _bookRepository; - private readonly IRepository _phoneInSecondDbContextRepository; - - public Basic_Repository_Tests() - { - _personRepository = ServiceProvider.GetRequiredService>(); - _bookRepository = ServiceProvider.GetRequiredService>(); - _phoneInSecondDbContextRepository = ServiceProvider.GetRequiredService>(); - } - - [Fact] - public void GetPersonList() - { - _personRepository.GetList().Any().ShouldBeTrue(); - } - - [Fact] - public void GetBookList() - { - _bookRepository.GetList().Any().ShouldBeTrue(); - } - - [Fact] - public void GetPhoneInSecondDbContextList() - { - _phoneInSecondDbContextRepository.GetList().Any().ShouldBeTrue(); - } - - [Fact] - public async Task InsertAsync() - { - var personId = Guid.NewGuid(); - - await _personRepository.InsertAsync(new Person(personId, "Adam", 42)); - - var person = await _personRepository.FindAsync(personId); - person.ShouldNotBeNull(); - } - } -} diff --git a/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/Repositories/Repository_Tests.cs b/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/Repositories/Repository_Tests.cs new file mode 100644 index 0000000000..f0ef9066f2 --- /dev/null +++ b/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/Repositories/Repository_Tests.cs @@ -0,0 +1,67 @@ +using System; +using System.Linq; +using System.Threading.Tasks; +using Microsoft.Extensions.DependencyInjection; +using Shouldly; +using Volo.Abp.Domain.Repositories; +using Volo.Abp.EntityFrameworkCore.TestApp.SecondContext; +using Volo.Abp.TestApp.Domain; +using Xunit; + +namespace Volo.Abp.EntityFrameworkCore.Repositories +{ + public class Repository_Tests : EntityFrameworkCoreTestBase + { + private readonly IRepository _personRepository; + private readonly IRepository _bookRepository; + private readonly IRepository _phoneInSecondDbContextRepository; + + public Repository_Tests() + { + _personRepository = ServiceProvider.GetRequiredService>(); + _bookRepository = ServiceProvider.GetRequiredService>(); + _phoneInSecondDbContextRepository = ServiceProvider.GetRequiredService>(); + } + + [Fact] + public void GetPersonList() + { + WithUnitOfWork(() => + { + _personRepository.Any().ShouldBeTrue(); + }); + } + + [Fact] + public void GetBookList() + { + WithUnitOfWork(() => + { + _bookRepository.Any().ShouldBeTrue(); + }); + } + + [Fact] + public void GetPhoneInSecondDbContextList() + { + WithUnitOfWork(() => + { + _phoneInSecondDbContextRepository.Any().ShouldBeTrue(); + }); + } + + [Fact] + public async Task InsertAsync() + { + await WithUnitOfWorkAsync(async () => + { + var personId = Guid.NewGuid(); + + await _personRepository.InsertAsync(new Person(personId, "Adam", 42)); + + var person = await _personRepository.FindAsync(personId); + person.ShouldNotBeNull(); + }); + } + } +} diff --git a/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/Transaction_Tests.cs b/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/Transaction_Tests.cs index 572b4efc3f..d37471ee9b 100644 --- a/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/Transaction_Tests.cs +++ b/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/EntityFrameworkCore/Transaction_Tests.cs @@ -12,14 +12,14 @@ namespace Volo.Abp.EntityFrameworkCore { public class Transaction_Tests : EntityFrameworkCoreTestBase { - private readonly IRepository _personRepository; - private readonly IRepository _bookRepository; + private readonly IBasicRepository _personRepository; + private readonly IBasicRepository _bookRepository; private readonly IUnitOfWorkManager _unitOfWorkManager; public Transaction_Tests() { - _personRepository = ServiceProvider.GetRequiredService>(); - _bookRepository = ServiceProvider.GetRequiredService>(); + _personRepository = ServiceProvider.GetRequiredService>(); + _bookRepository = ServiceProvider.GetRequiredService>(); _unitOfWorkManager = ServiceProvider.GetRequiredService(); } diff --git a/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/TestApp/EntityFrameworkCore/TestAppDbContext.cs b/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/TestApp/EntityFrameworkCore/TestAppDbContext.cs index f6088eb8a7..49deda972e 100644 --- a/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/TestApp/EntityFrameworkCore/TestAppDbContext.cs +++ b/test/Volo.Abp.EntityFrameworkCore.Tests/Volo/Abp/TestApp/EntityFrameworkCore/TestAppDbContext.cs @@ -16,5 +16,15 @@ namespace Volo.Abp.TestApp.EntityFrameworkCore { } + + protected override void OnModelCreating(ModelBuilder modelBuilder) + { + base.OnModelCreating(modelBuilder); + + modelBuilder.Entity(b => + { + b.HasKey(p => new {p.PersonId, p.Number}); + }); + } } } diff --git a/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/PersonAppServiceClientProxy_Tests.cs b/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/PersonAppServiceClientProxy_Tests.cs index e4af66fa62..568de29522 100644 --- a/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/PersonAppServiceClientProxy_Tests.cs +++ b/test/Volo.Abp.Http.Client.Tests/Volo/Abp/Http/DynamicProxying/PersonAppServiceClientProxy_Tests.cs @@ -15,18 +15,18 @@ namespace Volo.Abp.Http.DynamicProxying public class PersonAppServiceClientProxy_Tests : AbpHttpTestBase { private readonly IPeopleAppService _peopleAppService; - private readonly IRepository _personRepository; + private readonly IRepository _personRepository; public PersonAppServiceClientProxy_Tests() { _peopleAppService = ServiceProvider.GetRequiredService(); - _personRepository = ServiceProvider.GetRequiredService>(); + _personRepository = ServiceProvider.GetRequiredService>(); } [Fact] public async Task Get() { - var firstPerson = _personRepository.GetList().First(); + var firstPerson = _personRepository.First(); var person = await _peopleAppService.GetAsync(firstPerson.Id); person.ShouldNotBeNull(); @@ -45,11 +45,11 @@ namespace Volo.Abp.Http.DynamicProxying [Fact] public async Task Delete() { - var firstPerson = _personRepository.GetList().First(); + var firstPerson = _personRepository.First(); await _peopleAppService.DeleteAsync(firstPerson.Id); - firstPerson = _personRepository.GetList().FirstOrDefault(p => p.Id == firstPerson.Id); + firstPerson = _personRepository.FirstOrDefault(p => p.Id == firstPerson.Id); firstPerson.ShouldBeNull(); } @@ -69,7 +69,7 @@ namespace Volo.Abp.Http.DynamicProxying person.Id.ShouldNotBe(Guid.Empty); person.Name.ShouldBe(uniquePersonName); - var personInDb = _personRepository.GetList().FirstOrDefault(p => p.Name == uniquePersonName); + var personInDb = _personRepository.FirstOrDefault(p => p.Name == uniquePersonName); personInDb.ShouldNotBeNull(); personInDb.Id.ShouldBe(person.Id); } @@ -77,7 +77,7 @@ namespace Volo.Abp.Http.DynamicProxying [Fact] public async Task Update() { - var firstPerson = _personRepository.GetList().First(); + var firstPerson = _personRepository.First(); var uniquePersonName = Guid.NewGuid().ToString(); var person = await _peopleAppService.UpdateAsync( @@ -95,7 +95,7 @@ namespace Volo.Abp.Http.DynamicProxying person.Name.ShouldBe(uniquePersonName); person.Age.ShouldBe(firstPerson.Age); - var personInDb = _personRepository.GetList().FirstOrDefault(p => p.Id == firstPerson.Id); + var personInDb = _personRepository.FirstOrDefault(p => p.Id == firstPerson.Id); personInDb.ShouldNotBeNull(); personInDb.Id.ShouldBe(person.Id); personInDb.Name.ShouldBe(person.Name); diff --git a/test/Volo.Abp.Identity.Application.Tests/Volo/Abp/Identity/IdentityRoleAppService_Tests.cs b/test/Volo.Abp.Identity.Application.Tests/Volo/Abp/Identity/IdentityRoleAppService_Tests.cs index 1eedd46355..b73bb755fa 100644 --- a/test/Volo.Abp.Identity.Application.Tests/Volo/Abp/Identity/IdentityRoleAppService_Tests.cs +++ b/test/Volo.Abp.Identity.Application.Tests/Volo/Abp/Identity/IdentityRoleAppService_Tests.cs @@ -4,7 +4,6 @@ using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Xunit; using Shouldly; -using Volo.Abp.Application.Dtos; namespace Volo.Abp.Identity { diff --git a/test/Volo.Abp.Identity.Application.Tests/Volo/Abp/Identity/IdentityUserAppService_Tests.cs b/test/Volo.Abp.Identity.Application.Tests/Volo/Abp/Identity/IdentityUserAppService_Tests.cs index 7cb07c46b0..5c4f2f4a75 100644 --- a/test/Volo.Abp.Identity.Application.Tests/Volo/Abp/Identity/IdentityUserAppService_Tests.cs +++ b/test/Volo.Abp.Identity.Application.Tests/Volo/Abp/Identity/IdentityUserAppService_Tests.cs @@ -4,6 +4,7 @@ using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Shouldly; using Volo.Abp.Application.Dtos; +using Volo.Abp.Domain.Entities; using Xunit; namespace Volo.Abp.Identity @@ -184,12 +185,18 @@ namespace Volo.Abp.Identity private async Task GetUserAsync(string userName) { - return (await _userRepository.GetListAsync()).First(u => u.UserName == userName); + var user = await FindUserAsync(userName); + if (user == null) + { + throw new EntityNotFoundException(); + } + + return user; } private async Task FindUserAsync(string userName) { - return (await _userRepository.GetListAsync()).FirstOrDefault(u => u.UserName == userName); + return await _userRepository.FindByNormalizedUserNameAsync(userName.ToUpperInvariant()); } private static string CreateRandomEmail() diff --git a/test/Volo.Abp.Identity.Tests/Volo/Abp/Identity/Initialize_Tests.cs b/test/Volo.Abp.Identity.Tests/Volo/Abp/Identity/Initialize_Tests.cs index 3eca23445e..69b50be7f7 100644 --- a/test/Volo.Abp.Identity.Tests/Volo/Abp/Identity/Initialize_Tests.cs +++ b/test/Volo.Abp.Identity.Tests/Volo/Abp/Identity/Initialize_Tests.cs @@ -26,11 +26,11 @@ namespace Volo.Abp.Identity { (ServiceProvider.GetRequiredService() is EfCoreIdentityUserRepository).ShouldBeTrue(); - (ServiceProvider.GetRequiredService>() is EfCoreIdentityUserRepository).ShouldBeTrue(); - (ServiceProvider.GetRequiredService>() is EfCoreIdentityUserRepository).ShouldBeTrue(); + (ServiceProvider.GetRequiredService>() is EfCoreIdentityUserRepository).ShouldBeTrue(); + //(ServiceProvider.GetRequiredService>() is EfCoreIdentityUserRepository).ShouldBeTrue(); - (ServiceProvider.GetRequiredService>() is EfCoreIdentityUserRepository).ShouldBeTrue(); - (ServiceProvider.GetRequiredService>() is EfCoreIdentityUserRepository).ShouldBeTrue(); + (ServiceProvider.GetRequiredService>() is EfCoreIdentityUserRepository).ShouldBeTrue(); + //(ServiceProvider.GetRequiredService>() is EfCoreIdentityUserRepository).ShouldBeTrue(); } } } diff --git a/test/Volo.Abp.MemoryDb.Tests/Volo/Abp/MemoryDb/DataFilters/MemoryDb_SoftDelete_DataFilter_Tests.cs b/test/Volo.Abp.MemoryDb.Tests/Volo/Abp/MemoryDb/DataFilters/MemoryDb_SoftDelete_DataFilter_Tests.cs index d627dfbabd..1d73b94561 100644 --- a/test/Volo.Abp.MemoryDb.Tests/Volo/Abp/MemoryDb/DataFilters/MemoryDb_SoftDelete_DataFilter_Tests.cs +++ b/test/Volo.Abp.MemoryDb.Tests/Volo/Abp/MemoryDb/DataFilters/MemoryDb_SoftDelete_DataFilter_Tests.cs @@ -1,4 +1,5 @@ -using System.Linq; +using System; +using System.Linq; using Microsoft.Extensions.DependencyInjection; using Shouldly; using Volo.Abp.Data; @@ -10,12 +11,12 @@ namespace Volo.Abp.MemoryDb.DataFilters { public class MemoryDb_SoftDelete_DataFilter_Tests : MemoryDbTestBase { - private readonly IQueryableRepository _personRepository; + private readonly IRepository _personRepository; private readonly IDataFilter _dataFilter; public MemoryDb_SoftDelete_DataFilter_Tests() { - _personRepository = ServiceProvider.GetRequiredService>(); + _personRepository = ServiceProvider.GetRequiredService>(); _dataFilter = GetRequiredService(); } @@ -23,33 +24,33 @@ namespace Volo.Abp.MemoryDb.DataFilters public void Should_Get_Deleted_Entities_When_Filter_Is_Disabled() { //Soft delete is enabled by default - var people = _personRepository.GetList(); + var people = _personRepository.ToList(); people.Any(p => !p.IsDeleted).ShouldBeTrue(); people.Any(p => p.IsDeleted).ShouldBeFalse(); using (_dataFilter.Disable()) { //Soft delete is disabled - people = _personRepository.GetList(); + people = _personRepository.ToList(); people.Any(p => !p.IsDeleted).ShouldBeTrue(); people.Any(p => p.IsDeleted).ShouldBeTrue(); using (_dataFilter.Enable()) { //Soft delete is enabled again - people = _personRepository.GetList(); + people = _personRepository.ToList(); people.Any(p => !p.IsDeleted).ShouldBeTrue(); people.Any(p => p.IsDeleted).ShouldBeFalse(); } //Soft delete is disabled (restored previous state) - people = _personRepository.GetList(); + people = _personRepository.ToList(); people.Any(p => !p.IsDeleted).ShouldBeTrue(); people.Any(p => p.IsDeleted).ShouldBeTrue(); } //Soft delete is enabled (restored previous state) - people = _personRepository.GetList(); + people = _personRepository.ToList(); people.Any(p => !p.IsDeleted).ShouldBeTrue(); people.Any(p => p.IsDeleted).ShouldBeFalse(); } diff --git a/test/Volo.Abp.MemoryDb.Tests/Volo/Abp/MemoryDb/DataFilters/MultiTenant_Filter_Tests.cs b/test/Volo.Abp.MemoryDb.Tests/Volo/Abp/MemoryDb/DataFilters/MultiTenant_Filter_Tests.cs index 33d79461e4..d5bd1eff73 100644 --- a/test/Volo.Abp.MemoryDb.Tests/Volo/Abp/MemoryDb/DataFilters/MultiTenant_Filter_Tests.cs +++ b/test/Volo.Abp.MemoryDb.Tests/Volo/Abp/MemoryDb/DataFilters/MultiTenant_Filter_Tests.cs @@ -1,7 +1,6 @@ using System; using System.Collections.Generic; using System.Linq; -using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using NSubstitute; using Shouldly; @@ -17,12 +16,12 @@ namespace Volo.Abp.MemoryDb.DataFilters public class MemoryDb_MultiTenant_Filter_Tests : MemoryDbTestBase { private ICurrentTenant _fakeCurrentTenant; - private readonly IRepository _personRepository; + private readonly IRepository _personRepository; private readonly IDataFilter _multiTenantFilter; public MemoryDb_MultiTenant_Filter_Tests() { - _personRepository = GetRequiredService>(); + _personRepository = GetRequiredService>(); _multiTenantFilter = GetRequiredService>(); } @@ -33,13 +32,13 @@ namespace Volo.Abp.MemoryDb.DataFilters } [Fact] - public async Task Should_Get_Person_For_Current_Tenant() + public void Should_Get_Person_For_Current_Tenant() { //TenantId = null _fakeCurrentTenant.Id.Returns((Guid?)null); - var people = await _personRepository.GetListAsync(); + var people = _personRepository.ToList(); people.Count.ShouldBe(1); people.Any(p => p.Name == "Douglas").ShouldBeTrue(); @@ -47,7 +46,7 @@ namespace Volo.Abp.MemoryDb.DataFilters _fakeCurrentTenant.Id.Returns(TestDataBuilder.TenantId1); - people = await _personRepository.GetListAsync(); + people = _personRepository.ToList(); people.Count.ShouldBe(2); people.Any(p => p.Name == TestDataBuilder.TenantId1 + "-Person1").ShouldBeTrue(); people.Any(p => p.Name == TestDataBuilder.TenantId1 + "-Person2").ShouldBeTrue(); @@ -56,24 +55,24 @@ namespace Volo.Abp.MemoryDb.DataFilters _fakeCurrentTenant.Id.Returns(TestDataBuilder.TenantId2); - people = await _personRepository.GetListAsync(); + people = _personRepository.ToList(); people.Count.ShouldBe(0); } [Fact] - public async Task Should_Get_All_People_When_MultiTenant_Filter_Is_Disabled() + public void Should_Get_All_People_When_MultiTenant_Filter_Is_Disabled() { List people; using (_multiTenantFilter.Disable()) { //Filter disabled manually - people = await _personRepository.GetListAsync(); + people = _personRepository.ToList(); people.Count.ShouldBe(3); } //Filter re-enabled automatically - people = await _personRepository.GetListAsync(); + people = _personRepository.ToList(); people.Count.ShouldBe(1); } } diff --git a/test/Volo.Abp.MemoryDb.Tests/Volo/Abp/MemoryDb/Repositories/MemoryDb_Basic_Repository_Tests.cs b/test/Volo.Abp.MemoryDb.Tests/Volo/Abp/MemoryDb/Repositories/MemoryDb_Basic_Repository_Tests.cs index 768460f0ba..f96cbf7107 100644 --- a/test/Volo.Abp.MemoryDb.Tests/Volo/Abp/MemoryDb/Repositories/MemoryDb_Basic_Repository_Tests.cs +++ b/test/Volo.Abp.MemoryDb.Tests/Volo/Abp/MemoryDb/Repositories/MemoryDb_Basic_Repository_Tests.cs @@ -10,17 +10,17 @@ namespace Volo.Abp.MemoryDb.Repositories { public class MemoryDb_Basic_Repository_Tests : MemoryDbTestBase { - private readonly IQueryableRepository _personRepository; + private readonly IRepository _personRepository; public MemoryDb_Basic_Repository_Tests() { - _personRepository = ServiceProvider.GetRequiredService>(); + _personRepository = ServiceProvider.GetRequiredService>(); } [Fact] public void GetList() { - var people = _personRepository.GetList(); + var people = _personRepository.ToList(); people.Count.ShouldBeGreaterThan(0); } diff --git a/test/Volo.Abp.TestApp/Volo/Abp/TestApp/Application/Dto/PersonDto.cs b/test/Volo.Abp.TestApp/Volo/Abp/TestApp/Application/Dto/PersonDto.cs index 7075c0c3c9..57204f260f 100644 --- a/test/Volo.Abp.TestApp/Volo/Abp/TestApp/Application/Dto/PersonDto.cs +++ b/test/Volo.Abp.TestApp/Volo/Abp/TestApp/Application/Dto/PersonDto.cs @@ -1,8 +1,9 @@ -using Volo.Abp.Application.Dtos; +using System; +using Volo.Abp.Application.Dtos; namespace Volo.Abp.TestApp.Application.Dto { - public class PersonDto : EntityDto + public class PersonDto : EntityDto { public string Name { get; set; } diff --git a/test/Volo.Abp.TestApp/Volo/Abp/TestApp/Application/Dto/PhoneDto.cs b/test/Volo.Abp.TestApp/Volo/Abp/TestApp/Application/Dto/PhoneDto.cs index 203d4f5054..a71da2940a 100644 --- a/test/Volo.Abp.TestApp/Volo/Abp/TestApp/Application/Dto/PhoneDto.cs +++ b/test/Volo.Abp.TestApp/Volo/Abp/TestApp/Application/Dto/PhoneDto.cs @@ -1,9 +1,8 @@ -using Volo.Abp.Application.Dtos; -using Volo.Abp.TestApp.Domain; +using Volo.Abp.TestApp.Domain; namespace Volo.Abp.TestApp.Application.Dto { - public class PhoneDto : EntityDto + public class PhoneDto { public string Number { get; set; } diff --git a/test/Volo.Abp.TestApp/Volo/Abp/TestApp/Application/IPeopleAppService.cs b/test/Volo.Abp.TestApp/Volo/Abp/TestApp/Application/IPeopleAppService.cs index 9a0188d96d..6317d7d8ce 100644 --- a/test/Volo.Abp.TestApp/Volo/Abp/TestApp/Application/IPeopleAppService.cs +++ b/test/Volo.Abp.TestApp/Volo/Abp/TestApp/Application/IPeopleAppService.cs @@ -6,13 +6,13 @@ using Volo.Abp.TestApp.Application.Dto; namespace Volo.Abp.TestApp.Application { - public interface IPeopleAppService : IAsyncCrudAppService + public interface IPeopleAppService : IAsyncCrudAppService { Task> GetPhones(Guid id, GetPersonPhonesFilter filter); Task AddPhone(Guid id, PhoneDto phoneDto); - Task RemovePhone(Guid id, long phoneId); + Task RemovePhone(Guid id, string number); Task GetWithComplexType(GetWithComplexTypeInput input); } diff --git a/test/Volo.Abp.TestApp/Volo/Abp/TestApp/Application/PeopleAppService.cs b/test/Volo.Abp.TestApp/Volo/Abp/TestApp/Application/PeopleAppService.cs index 0561f6fcef..05c6afb7dc 100644 --- a/test/Volo.Abp.TestApp/Volo/Abp/TestApp/Application/PeopleAppService.cs +++ b/test/Volo.Abp.TestApp/Volo/Abp/TestApp/Application/PeopleAppService.cs @@ -10,9 +10,9 @@ using Volo.Abp.TestApp.Application.Dto; namespace Volo.Abp.TestApp.Application { - public class PeopleAppService : AsyncCrudAppService, IPeopleAppService + public class PeopleAppService : AsyncCrudAppService, IPeopleAppService { - public PeopleAppService(IQueryableRepository repository) + public PeopleAppService(IRepository repository) : base(repository) { @@ -39,10 +39,10 @@ namespace Volo.Abp.TestApp.Application return ObjectMapper.Map(phone); } - public async Task RemovePhone(Guid id, long phoneId) + public async Task RemovePhone(Guid id, string number) { var person = await GetEntityByIdAsync(id); - person.Phones.RemoveAll(p => p.Id == phoneId); + person.Phones.RemoveAll(p => p.Number == number); } public Task GetWithComplexType(GetWithComplexTypeInput input) diff --git a/test/Volo.Abp.TestApp/Volo/Abp/TestApp/Domain/Person.cs b/test/Volo.Abp.TestApp/Volo/Abp/TestApp/Domain/Person.cs index 6f91db9c30..7754f16cda 100644 --- a/test/Volo.Abp.TestApp/Volo/Abp/TestApp/Domain/Person.cs +++ b/test/Volo.Abp.TestApp/Volo/Abp/TestApp/Domain/Person.cs @@ -1,11 +1,13 @@ using System; using System.Collections.ObjectModel; +using Volo.Abp.Application.Services; using Volo.Abp.Domain.Entities; +using Volo.Abp.Domain.Repositories; using Volo.Abp.MultiTenancy; namespace Volo.Abp.TestApp.Domain { - public class Person : AggregateRoot, IMultiTenant, ISoftDelete + public class Person : AggregateRoot, IMultiTenant, ISoftDelete { public virtual Guid? TenantId { get; set; } diff --git a/test/Volo.Abp.TestApp/Volo/Abp/TestApp/Domain/Phone.cs b/test/Volo.Abp.TestApp/Volo/Abp/TestApp/Domain/Phone.cs index 8519bea092..142e97463e 100644 --- a/test/Volo.Abp.TestApp/Volo/Abp/TestApp/Domain/Phone.cs +++ b/test/Volo.Abp.TestApp/Volo/Abp/TestApp/Domain/Phone.cs @@ -1,11 +1,13 @@ using System; +using System.Collections.Generic; using System.ComponentModel.DataAnnotations.Schema; +using System.Linq; using Volo.Abp.Domain.Entities; namespace Volo.Abp.TestApp.Domain { [Table("AppPhones")] - public class Phone : Entity + public class Phone : Entity { public virtual Guid PersonId { get; set; } @@ -25,4 +27,74 @@ namespace Volo.Abp.TestApp.Domain Type = type; } } + + public class Order : AggregateRoot + { + public virtual string ReferenceNo { get; protected set; } + + public virtual float TotalItemCount { get; protected set; } + + public virtual DateTime CreationTime { get; protected set; } + + public virtual List OrderLines { get; protected set; } + + protected Order() + { + + } + + public Order(Guid id, string referenceNo) + { + Id = id; + ReferenceNo = referenceNo; + OrderLines = new List(); + } + + public void AddProduct(Guid productId, int count) + { + if (count <= 0) + { + throw new ArgumentException("You can not add zero or negative count of products!", nameof(count)); + } + + var existingLine = OrderLines.FirstOrDefault(ol => ol.ProductId == productId); + + if (existingLine == null) + { + OrderLines.Add(new OrderLine(this.Id, productId, count)); + } + else + { + existingLine.ChangeCount(existingLine.Count + count); + } + + TotalItemCount += count; + } + } + + public class OrderLine : Entity + { + public virtual Guid OrderId { get; protected set; } + + public virtual Guid ProductId { get; protected set; } + + public virtual int Count { get; protected set; } + + protected OrderLine() + { + + } + + public OrderLine(Guid orderId, Guid productId, int count) + { + OrderId = orderId; + ProductId = productId; + Count = count; + } + + internal void ChangeCount(int newCount) + { + Count = newCount; + } + } } \ No newline at end of file diff --git a/test/Volo.Abp.TestApp/Volo/Abp/TestApp/TestDataBuilder.cs b/test/Volo.Abp.TestApp/Volo/Abp/TestApp/TestDataBuilder.cs index 80e6e8e2a7..edc94b51ff 100644 --- a/test/Volo.Abp.TestApp/Volo/Abp/TestApp/TestDataBuilder.cs +++ b/test/Volo.Abp.TestApp/Volo/Abp/TestApp/TestDataBuilder.cs @@ -10,9 +10,9 @@ namespace Volo.Abp.TestApp public static Guid TenantId1 { get; } = new Guid("55687dce-595c-41b4-a024-2a5e991ac8f4"); public static Guid TenantId2 { get; } = new Guid("f522d19f-5a86-4278-98fb-0577319c544a"); - private readonly IRepository _personRepository; + private readonly IBasicRepository _personRepository; - public TestDataBuilder(IRepository personRepository) + public TestDataBuilder(IBasicRepository personRepository) { _personRepository = personRepository; }