ABP框架 實現簡單電話本(增刪改查)功能(ASP.NET Core V2.x +Multi Page Web Application)

內容是按照電話薄實例這個視頻寫的,後面自己實在是不想寫過程了(我太懶了),就把視頻鏈接放上來了。視頻裏面的MPA版本代碼放到現在的ABP框架版本(4.8.0)裏面會有些錯誤和有的方法已經被棄用,在這篇文章裏我把這些地方總結一下,其他的就可以按照視頻裏的代碼編寫就可以了。

完整代碼:電話薄實例

第一步:(core層)創建實體Person和PhoneNumber ,以及Person和PhoneNumber之間的關聯

using Abp.Domain.Entities.Auditing;
using MyPhoneBook.Core.PhoneBooks.PhoneNumbers;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;

namespace MyPhoneBook.Core.PhoneBooks.Persons
{    
    public class Person:FullAuditedEntity
    {
        [Required]
        [MaxLength(MyPhoneBookConsts.MaxNameLength)]
        public string Name { get; set; }

        [MaxLength(MyPhoneBookConsts.MaxEmailLength)]
        [EmailAddress]
        public string EmailAddress { get; set; }

        [MaxLength(MyPhoneBookConsts.MaxAddressLength)]
        public string Address { get; set; }
        /// <summary>
        /// 電話號碼的屬性,Person與PhoneNumber進行關聯
        /// </summary>
        public ICollection<PhoneNumber> PhoneNumbers { get; set; }
    }
}
using Abp.Domain.Entities;
using Abp.Domain.Entities.Auditing;
using MyPhoneBook.Core.PhoneBooks.Persons;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;

namespace MyPhoneBook.Core.PhoneBooks.PhoneNumbers
{
    public class PhoneNumber:Entity<long>,IHasCreationTime
    {
        [Required]
        [MaxLength(MyPhoneBookConsts.MaxPhoneNumberLength)]
        public string Number { get; set; }

        public PhoneNumberType PhoneNumberType { get; set; }
        public DateTime CreationTime { get; set; }

        public int PersonId { get; set; }
        public Person Persons { get; set; }
    }
}

using System;
using System.Collections.Generic;
using System.Text;

namespace MyPhoneBook.Core.PhoneBooks.PhoneNumbers
{
    public enum PhoneNumberType
    {
        Moblie=1,
        Home=2,
        Company=3
    }
}

在MyPhoneBookConsts.cs中添加下面的代碼

        public const int MaxNameLength = 50;
        public const int MaxAddressLength = 200;
        public const int MaxEmailLength = 80;
        public const int MaxPhoneNumberLength = 11;

第二步:(EntityFrameworkCore層)將實體映射到數據庫中

在MyPhoneBookDbContext.cs添加代碼

using Microsoft.EntityFrameworkCore;
using Abp.Zero.EntityFrameworkCore;
using MyPhoneBook.Authorization.Roles;
using MyPhoneBook.Authorization.Users;
using MyPhoneBook.MultiTenancy;
using MyPhoneBook.Core.PhoneBooks.Persons;
using MyPhoneBook.Core.PhoneBooks.PhoneNumbers;

namespace MyPhoneBook.EntityFrameworkCore
{
    public class MyPhoneBookDbContext : AbpZeroDbContext<Tenant, Role, User, MyPhoneBookDbContext>
    {
        /* Define a DbSet for each entity of the application */
        public DbSet<Person> Persons { get; set; }
        public DbSet<PhoneNumber> PhoneNumbers { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Person>().ToTable("Person", "PB");
            modelBuilder.Entity<PhoneNumber>().ToTable("PhoneNumber", "PB");
            base.OnModelCreating(modelBuilder);
        }
        public MyPhoneBookDbContext(DbContextOptions<MyPhoneBookDbContext> options)
            : base(options)
        {
        }
    }
}

第三步:(Application層) 編寫應用服務以及Dto

1、分頁和排序輸入Dto(PagedAndSortedInputDto)

using Abp.Application.Services.Dto;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Text;

namespace MyPhoneBook.Application.Dto
{
    public class PagedAndSortedInputDto : IPagedResultRequest, ISortedResultRequest
    {
        
        public string Sorting { get; set; }
        [Range(0,int.MaxValue)]
        public int SkipCount { get ; set; }
        [Range(1,500)]
        public int MaxResultCount { get; set; }
    }
}

2、

 

第四步:(Web層)編寫控制器、視圖

太晚了。。。今天不想寫了。。。

 

補充在這裏:

1、Web.Mvc->Startup->...NavigationProvider.cs

這個類的作用是在首頁的左側添加菜單欄

視頻中使用了分頁,所以URL就要寫清楚

這一點視頻裏沒有講,添加完這一行代碼,你就可以跳轉到聯繫人界面進行編寫功能了。

2、在使用到MapTo時,會出現一些綠色的波浪線,提示你它已經被棄用了 ,把它修改成ObjectMapper

using Abp.Application.Services.Dto;
using Abp.AutoMapper;
using Abp.Domain.Repositories;
using Abp.Linq.Extensions;
using Abp.ObjectMapping;
using Abp.UI;
using Microsoft.EntityFrameworkCore;
using MyPhoneBook.Application.Dto;
using MyPhoneBook.Application.PhoneBooks.Dtos;
using MyPhoneBook.Core.PhoneBooks.Persons;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading.Tasks;

namespace MyPhoneBook.Application.PhoneBooks
{
    public class PersonAppService : MyPhoneBookAppServiceBase, IPersonAppService
    {
        private readonly IRepository<Person> _personRepository;
       // private readonly IObjectMapper _objectMapper;
        public PersonAppService(IRepository<Person> personRepository)
        {
            _personRepository = personRepository;
           
        }
       //public PersonAppService(IRepository<Person> personRepository, IObjectMapper objectMapper)
       // {
         //   _personRepository = personRepository;
          //  _objectMapper = objectMapper;
      // }
        public async Task CreateOrUpdatePersonAsync(CreateOrUpdatePersonInput input)
        {
            if(input.PersonEditDto.Id.HasValue)
            {
                await UpdatePersonAsync(input.PersonEditDto);

            }
            else
            {
                await CreatePersonAsync(input.PersonEditDto);
            }
        }
        protected async Task CreatePersonAsync(PersonEditDto input)
        {
            var entity = ObjectMapper.Map<Person>(input);
            await _personRepository.InsertAsync(entity);
        }
        protected async Task UpdatePersonAsync(PersonEditDto input)
        {
            var entity = await _personRepository.GetAsync(input.Id.Value);//先查詢一下
             //await _personRepository.UpdateAsync(input.MapTo(entity));
            
            await _personRepository.UpdateAsync(ObjectMapper.Map(input,entity));
        }
        public async Task DeletePersonAsync(EntityDto input)
        {
            var entity = await _personRepository.GetAsync(input.Id);//查詢這個id是否存在
            if (entity == null)
            {
                throw new UserFriendlyException("該聯繫人已經消失在數據庫中了,無法二次刪除!");
            }
            await _personRepository.DeleteAsync(input.Id);
        }

        public async Task<PagedResultDto<PersonListDto>> GetPagedPersonAsync(GetPersonInput input)
        {
            var query = _personRepository.GetAllIncluding(a => a.PhoneNumbers);//這個只是相當於SQL語句,後面使用的是λ表達式
            var personCount = await query.CountAsync();//統計條數
            var persons = await query.OrderBy(input.Sorting).PageBy(input).ToListAsync();//Sorting是按Id進行排序的
            // var dtos = persons.MapTo<List<PersonListDto>>();//這個方法過時了
            var dtos = ObjectMapper.Map<List<PersonListDto>>(persons);
            return new PagedResultDto<PersonListDto>(personCount, dtos);
        }

        public async Task<PersonListDto> GetPersonByIdAsync(NullableIdDto input)
        {
            var person = await _personRepository.GetAllIncluding(a => a.PhoneNumbers).FirstOrDefaultAsync(a => a.Id == input.Id.Value);
            //  return person.MapTo<PersonListDto>();
            return ObjectMapper.Map<PersonListDto>(person);
        }

        public async Task<GetPersonForEditOutput> GetPersonForEditAsync(NullableIdDto<int> input)
        {
            var output = new GetPersonForEditOutput();
            PersonEditDto personEditDto;
            if (input.Id.HasValue)
            {
                var entity = await _personRepository.GetAllIncluding(a => a.PhoneNumbers).FirstOrDefaultAsync(a => a.Id == input.Id.Value);
              // personEditDto = entity.MapTo<PersonEditDto>();
                  personEditDto = ObjectMapper.Map<PersonEditDto>(entity);
            }
            else
            {
                personEditDto = new PersonEditDto();
            }
            output.Person = personEditDto;
            return output;
        }
    }
}

3、當你按照視頻把項目寫完時,運行一下,在使用編輯功能時,會提示錯誤,這時指示提示了一個ABP給我們展示的一個很友好的錯誤提示,我們根本不知道到底是哪裏發生了錯誤,這時就要讓ABP顯示報錯的具體信息,ABP框架查看前端完整錯誤提示,根據這個文章改好,就可以看到具體錯誤的信息了,這時我們就看到提示是映射的問題,我們就按照提示進行修改

修改PersonEditDto.cs和PhoneNumberEditDto.cs這兩個文件中的映射,將視頻中寫的AutoMapTo,修改AutoMap。

到這裏代碼就可以正確運行了!

 

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章