- вынес необходимую логику в репозитории.

- поменял состав моделей представления.
- удалил ненужные модели представления.
- добавил сервисы.
- отрефакторил код.

Partial.
parent fcbec971
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using PhoneStore.Enums;
using PhoneStore.Helpers;
using PhoneStore.Models;
using PhoneStore.Services.Interfaces;
using PhoneStore.ViewModels.Account;
......@@ -11,10 +14,13 @@ namespace PhoneStore.Controllers
public class AccountController : Controller
{
private readonly IAccountService _accountService;
private readonly UserManager<User> _userManager;
public AccountController(IAccountService accountService)
public AccountController(IAccountService accountService, UserManager<User> userManager)
{
_accountService = accountService;
_userManager = userManager;
}
[HttpGet]
......@@ -80,5 +86,12 @@ namespace PhoneStore.Controllers
var users = _accountService.SearchUsersByAnyTerm(searchTerm);
return PartialView("PartialViews/SearchResultPartial", users);
}
[HttpGet]
public async Task<OkObjectResult> GetAuthUser()
{
User user = await _userManager.GetUserAsync(User);
return Ok(user ?? new User());
}
}
}
\ No newline at end of file
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using PhoneStore.Mappers;
using PhoneStore.Models;
using PhoneStore.Services.Interfaces;
using PhoneStore.ViewModels;
namespace PhoneStore.Controllers
{
public class OrdersController : Controller
{
private readonly MobileContext _db;
public OrdersController(MobileContext db)
private readonly IOrderService _orderService;
private readonly IPhoneService _phoneService;
private readonly UserManager<User> _userManager;
public OrdersController(IOrderService orderService, IPhoneService phoneService, UserManager<User> userManager)
{
_db = db;
_orderService = orderService;
_phoneService = phoneService;
_userManager = userManager;
}
// GET
[HttpGet]
public IActionResult Index()
{
var orders = _db.Orders
.Include(p => p.Phone)
.ToList();
var orders = _orderService.GetAll();
return View(orders);
}
[HttpGet]
public IActionResult Create(int phoneId)
public async Task<IActionResult> Create(int phoneId)
{
var phone = _db.Phones.FirstOrDefault(p => p.Id == phoneId);
User user = await _userManager.GetUserAsync(User);
var phone = _phoneService.GetById(phoneId);
if (phone is null)
return RedirectToAction("Error", "Errors", new {statusCode = 777});
Order order = new Order
OrderViewModel order = new OrderViewModel
{
Phone = phone
Phone = phone,
User = user.MapToUserViewModel()
};
return View(order);
}
[HttpPost]
public IActionResult Create(Order order)
public IActionResult Create(OrderViewModel order)
{
_db.Orders.Add(order);
_db.SaveChanges();
order.UserId = int.Parse(_userManager.GetUserId(User));
_orderService.Create(order.MapToOrderViewModel());
return RedirectToAction("Index");
}
}
......
......@@ -6,6 +6,7 @@ using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using PhoneStore.Helpers;
using PhoneStore.Mappers;
using PhoneStore.Models;
using PhoneStore.Services.Interfaces;
using PhoneStore.ViewModels;
......@@ -143,7 +144,7 @@ namespace PhoneStore.Controllers
try
{
if (!phoneId.HasValue) return RedirectToAction("Error", "Errors", new {statusCode = 777});
var phoneViewModel = _phoneService.GetPhoneById((int)phoneId);
var phoneViewModel = _phoneService.GetById(phoneId.Value);
return View(phoneViewModel);
}
catch (NullReferenceException)
......
using Microsoft.Extensions.DependencyInjection;
using PhoneStore.Repositories;
using PhoneStore.Repositories.Interfaces;
namespace PhoneStore.Helpers
{
public static class RepositoryConnector
{
public static IServiceCollection AddRepositories(IServiceCollection services)
{
services.AddScoped<IFeedbackRepository, FeedbackRepository>();
services.AddScoped<IOrderRepository, OrderRepository>();
services.AddScoped<IPhoneRepository, PhoneRepository>();
return services;
}
}
}
\ No newline at end of file
......@@ -8,7 +8,7 @@ namespace PhoneStore.Helpers
{
public static class ServiceConnector
{
public static void AddApplicationServices(this IServiceCollection services, IConfiguration configuration)
public static IServiceCollection AddApplicationServices(this IServiceCollection services, IConfiguration configuration)
{
services.AddScoped<IBasketService, BasketService>();
services.AddTransient<UploadService>();
......@@ -24,6 +24,9 @@ namespace PhoneStore.Helpers
services.AddTransient<IAccountService, AccountService>();
services.AddTransient<IUsersSearcher, UsersSearcher>();
services.AddTransient<IFeedbackService, FeedbackService>();
services.AddTransient<IPhoneService, PhoneService>();
services.AddTransient<IOrderService, OrderService>();
return services;
}
}
}
\ No newline at end of file
using PhoneStore.Models;
using PhoneStore.ViewModels.Feedback;
namespace PhoneStore.Helpers
namespace PhoneStore.Mappers
{
public static class FeedbackMapper
{
......@@ -19,5 +19,20 @@ namespace PhoneStore.Helpers
};
return feedbackViewModel;
}
public static Feedback MapToFeedback(this FeedbackViewModel self)
{
Feedback feedbackViewModel = new Feedback
{
Id = self.Id,
Text = self.Text,
PhoneId = self.PhoneId,
UserId = self.UserId,
User = self.User.MapToUser(),
Phone = self.Phone.MapToPhone(),
CreationDateTime = self.CreationDateTime
};
return feedbackViewModel;
}
}
}
\ No newline at end of file
using PhoneStore.Models;
using PhoneStore.ViewModels;
namespace PhoneStore.Mappers
{
public static class OrderMapper
{
public static OrderViewModel MapToOrderViewModel(this Order self)
{
return new OrderViewModel
{
Address = self.Address,
Phone = self.Phone.MapToPhoneViewModel(),
ContactPhone = self.ContactPhone,
PhoneId = self.PhoneId,
User = self.User.MapToUserViewModel(),
UserId = self.UserId,
Id = self.Id
};
}
public static Order MapToOrderViewModel(this OrderViewModel self)
{
return new Order
{
Address = self.Address,
Phone = self.Phone?.MapToPhone(),
ContactPhone = self.ContactPhone,
PhoneId = self.PhoneId,
User = self.User?.MapToUser(),
UserId = self.UserId,
Id = self.Id
};
}
}
}
\ No newline at end of file
using System.Linq;
using PhoneStore.Models;
using PhoneStore.ViewModels;
using PhoneStore.ViewModels.PhoneViewModels;
namespace PhoneStore.Helpers
namespace PhoneStore.Mappers
{
public static class PhoneMapper
{
......@@ -19,19 +19,35 @@ namespace PhoneStore.Helpers
return phone;
}
public static PhoneViewModel MapToPhoneViewModel(this Phone self, string imagePath = null)
public static PhoneViewModel MapToPhoneViewModel(this Phone self)
{
PhoneViewModel phone = new PhoneViewModel
{
Name = self.Name,
Price = self.Price,
Brand = self.Brand,
Image = imagePath,
Id = self.Id
Image = self.Image,
Id = self.Id,
Feedbacks = self.Feedbacks.Select(f => f.MapToFeedbackViewModel()),
BrandId = self.BrandId
};
return phone;
}
public static Phone MapToPhone(this PhoneViewModel self, string imagePath = null)
{
Phone phone = new Phone
{
Name = self.Name,
Price = self.Price,
BrandId = self.BrandId,
Image = imagePath,
Id = self.Id,
Brand = self.Brand
};
return phone;
}
}
}
\ No newline at end of file
......@@ -3,9 +3,9 @@ using PhoneStore.Models;
using PhoneStore.ViewModels;
using PhoneStore.ViewModels.Account;
namespace PhoneStore.Helpers
namespace PhoneStore.Mappers
{
public static class UserHelper
public static class UserMapper
{
public static UsersViewModel MapToUsersViewModel(
this IQueryable<User> self,
......@@ -22,8 +22,7 @@ namespace PhoneStore.Helpers
};
}
public static UserViewModel MapToUserViewModel(
this User self)
public static UserViewModel MapToUserViewModel(this User self)
{
return new UserViewModel
{
......@@ -34,5 +33,16 @@ namespace PhoneStore.Helpers
Username = self.UserName
};
}
public static User MapToUser(this UserViewModel self)
{
return new User
{
Age = self.Age,
Email = self.Email,
Id = self.Id,
Name = self.Name
};
}
}
}
\ No newline at end of file
This diff is collapsed.
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
namespace PhoneStore.Migrations
{
public partial class AddUserField : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "UserName",
table: "Orders");
migrationBuilder.AddColumn<int>(
name: "UserId",
table: "Orders",
type: "integer",
nullable: false,
defaultValue: 0);
migrationBuilder.CreateTable(
name: "SubscriptionsSubscribers",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
SubscriberId = table.Column<int>(type: "integer", nullable: false),
SubscriptionId = table.Column<int>(type: "integer", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_SubscriptionsSubscribers", x => x.Id);
table.ForeignKey(
name: "FK_SubscriptionsSubscribers_AspNetUsers_SubscriberId",
column: x => x.SubscriberId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
table.ForeignKey(
name: "FK_SubscriptionsSubscribers_AspNetUsers_SubscriptionId",
column: x => x.SubscriptionId,
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_Orders_UserId",
table: "Orders",
column: "UserId");
migrationBuilder.CreateIndex(
name: "IX_SubscriptionsSubscribers_SubscriberId",
table: "SubscriptionsSubscribers",
column: "SubscriberId");
migrationBuilder.CreateIndex(
name: "IX_SubscriptionsSubscribers_SubscriptionId",
table: "SubscriptionsSubscribers",
column: "SubscriptionId");
migrationBuilder.AddForeignKey(
name: "FK_Orders_AspNetUsers_UserId",
table: "Orders",
column: "UserId",
principalTable: "AspNetUsers",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Orders_AspNetUsers_UserId",
table: "Orders");
migrationBuilder.DropTable(
name: "SubscriptionsSubscribers");
migrationBuilder.DropIndex(
name: "IX_Orders_UserId",
table: "Orders");
migrationBuilder.DropColumn(
name: "UserId",
table: "Orders");
migrationBuilder.AddColumn<string>(
name: "UserName",
table: "Orders",
type: "text",
nullable: true);
}
}
}
using Microsoft.EntityFrameworkCore.Migrations;
namespace PhoneStore.Migrations
{
public partial class RemoveNullable : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Phones_Brands_BrandId",
table: "Phones");
migrationBuilder.AlterColumn<int>(
name: "BrandId",
table: "Phones",
type: "integer",
nullable: false,
defaultValue: 0,
oldClrType: typeof(int),
oldType: "integer",
oldNullable: true);
migrationBuilder.AddForeignKey(
name: "FK_Phones_Brands_BrandId",
table: "Phones",
column: "BrandId",
principalTable: "Brands",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_Phones_Brands_BrandId",
table: "Phones");
migrationBuilder.AlterColumn<int>(
name: "BrandId",
table: "Phones",
type: "integer",
nullable: true,
oldClrType: typeof(int),
oldType: "integer");
migrationBuilder.AddForeignKey(
name: "FK_Phones_Brands_BrandId",
table: "Phones",
column: "BrandId",
principalTable: "Brands",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
}
}
......@@ -196,13 +196,15 @@ namespace PhoneStore.Migrations
b.Property<int>("PhoneId")
.HasColumnType("integer");
b.Property<string>("UserName")
.HasColumnType("text");
b.Property<int>("UserId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("PhoneId");
b.HasIndex("UserId");
b.ToTable("Orders");
});
......@@ -213,7 +215,7 @@ namespace PhoneStore.Migrations
.HasColumnType("integer")
.HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn);
b.Property<int?>("BrandId")
b.Property<int>("BrandId")
.HasColumnType("integer");
b.Property<string>("Image")
......@@ -260,6 +262,28 @@ namespace PhoneStore.Migrations
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("PhoneStore.Models.SubscriptionSubscriber", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("integer")
.HasAnnotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn);
b.Property<int>("SubscriberId")
.HasColumnType("integer");
b.Property<int>("SubscriptionId")
.HasColumnType("integer");
b.HasKey("Id");
b.HasIndex("SubscriberId");
b.HasIndex("SubscriptionId");
b.ToTable("SubscriptionsSubscribers");
});
modelBuilder.Entity("PhoneStore.Models.User", b =>
{
b.Property<int>("Id")
......@@ -397,7 +421,7 @@ namespace PhoneStore.Migrations
modelBuilder.Entity("PhoneStore.Models.Feedback", b =>
{
b.HasOne("PhoneStore.Models.Phone", "Phone")
.WithMany()
.WithMany("Feedbacks")
.HasForeignKey("PhoneId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
......@@ -421,17 +445,58 @@ namespace PhoneStore.Migrations
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("PhoneStore.Models.User", "User")
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Phone");
b.Navigation("User");
});
modelBuilder.Entity("PhoneStore.Models.Phone", b =>
{
b.HasOne("PhoneStore.Models.Brand", "Brand")
.WithMany()
.HasForeignKey("BrandId");
.HasForeignKey("BrandId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.Navigation("Brand");
});
modelBuilder.Entity("PhoneStore.Models.SubscriptionSubscriber", b =>
{
b.HasOne("PhoneStore.Models.User", "Subscriber")
.WithMany("Subscribers")
.HasForeignKey("SubscriberId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.HasOne("PhoneStore.Models.User", "Subscription")
.WithMany("Subscriptions")
.HasForeignKey("SubscriptionId")
.OnDelete(DeleteBehavior.Restrict)
.IsRequired();
b.Navigation("Subscriber");
b.Navigation("Subscription");
});
modelBuilder.Entity("PhoneStore.Models.Phone", b =>
{
b.Navigation("Feedbacks");
});
modelBuilder.Entity("PhoneStore.Models.User", b =>
{
b.Navigation("Subscribers");
b.Navigation("Subscriptions");
});
#pragma warning restore 612, 618
}
}
......
......@@ -13,6 +13,7 @@ namespace PhoneStore.Models
public MobileContext(DbContextOptions<MobileContext> options) : base(options)
{
}
}
}
\ No newline at end of file
......@@ -3,7 +3,8 @@ namespace PhoneStore.Models
public class Order
{
public int Id { get; set; }
public string UserName { get; set; }
public int UserId { get; set; }
public User User { get; set; }
public string ContactPhone { get; set; }
public string Address { get; set; }
......
......@@ -7,7 +7,7 @@ namespace PhoneStore.Models
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public int? BrandId { get; set; }
public int BrandId { get; set; }
public Brand Brand { get; set; }
public string Image { get; set; }
public List<Feedback> Feedbacks { get; set; }
......
using System.Collections.Generic;
using Microsoft.AspNetCore.Identity;
namespace PhoneStore.Models
......
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using PhoneStore.Models;
using PhoneStore.Repositories.Interfaces;
namespace PhoneStore.Repositories
{
public class FeedbackRepository : IFeedbackRepository
{
private readonly MobileContext _db;
public FeedbackRepository(MobileContext db)
{
_db = db;
}
public IEnumerable<Feedback> GetAllByUserId(int userId)
=> _db.Feedbacks.Where(f => f.UserId == userId);
public Feedback GetById(int id)
{
return _db.Feedbacks
.Include(f => f.User)
.Include(f => f.Phone)
.First(f => f.Id == id);
}
public bool CheckFeedbackExists(int userId, int phoneId)
=> _db.Feedbacks.Any(f => f.UserId == userId && f.PhoneId == phoneId);
public void Create(Feedback feedback)
{
_db.Feedbacks.Add(feedback);
_db.SaveChanges();
}
public void Update(Feedback feedback)
{
_db.Update(feedback);
_db.SaveChanges();
}
public IEnumerable<Order> GetByUserId(int id)
=> _db.Orders.Where(o => o.UserId == id);
}
}
\ No newline at end of file
namespace PhoneStore.Repositories.Interfaces.Base
{
public interface IBaseOperations<T>
{
void Create(T entity);
void Update(T entity);
T GetById(int id);
}
}
\ No newline at end of file
using System.Collections.Generic;
namespace PhoneStore.Repositories.Interfaces.Base
{
public interface IByUserIdProvider<out T>
{
IEnumerable<T> GetByUserId(int id);
}
}
\ No newline at end of file
using PhoneStore.Models;
using PhoneStore.Repositories.Interfaces.Base;
namespace PhoneStore.Repositories.Interfaces
{
public interface IFeedbackRepository : IBaseOperations<Feedback>, IByUserIdProvider<Order>
{
bool CheckFeedbackExists(int userId, int phoneId);
}
}
\ No newline at end of file

using System.Collections.Generic;
using PhoneStore.Models;
using PhoneStore.Repositories.Interfaces.Base;
namespace PhoneStore.Repositories.Interfaces
{
public interface IOrderRepository : IBaseOperations<Order>, IByUserIdProvider<Order>
{
IEnumerable<Order> GetAll();
}
}
\ No newline at end of file
using PhoneStore.Models;
using PhoneStore.Repositories.Interfaces.Base;
namespace PhoneStore.Repositories.Interfaces
{
public interface IPhoneRepository : IBaseOperations<Phone>
{
}
}
\ No newline at end of file
using System.Collections.Generic;
using System.Linq;
using Microsoft.EntityFrameworkCore;
using PhoneStore.Models;
using PhoneStore.Repositories.Interfaces;
namespace PhoneStore.Repositories
{
public class OrderRepository : IOrderRepository
{
private readonly MobileContext _db;
public OrderRepository(MobileContext db)
{
_db = db;
}
public void Create(Order order)
{
_db.Orders.Add(order);
_db.SaveChanges();
}
public void Update(Order order)
{
_db.Orders.Update(order);
_db.SaveChanges();
}
public Order GetById(int id)
=> _db.Orders
.Include(o => o.Phone)
.Include(o => o.User)
.FirstOrDefault(o => o.Id == id);
public IEnumerable<Order> GetAll()
{
return _db.Orders
.Include(p => p.Phone)
.Include(p => p.User)
.ToList();
}
public IEnumerable<Order> GetByUserId(int id)
=> _db.Orders
.Include(o => o.User)
.Include(o => o.Phone)
.Where(o => o.UserId == id);
}
}
\ No newline at end of file
using System.Linq;
using Microsoft.EntityFrameworkCore;
using PhoneStore.Models;
using PhoneStore.Repositories.Interfaces;
namespace PhoneStore.Repositories
{
public class PhoneRepository : IPhoneRepository
{
private readonly MobileContext _db;
public PhoneRepository(MobileContext db)
{
_db = db;
}
public void Create(Phone phone)
{
_db.Phones.Add(phone);
_db.SaveChanges();
}
public void Update(Phone phone)
{
_db.Phones.Update(phone);
_db.SaveChanges();
}
public Phone GetById(int id)
{
var a =_db.Phones
.Include(p => p.Brand)
.Include(p => p.Feedbacks)
.FirstOrDefault(p => p.Id == id);
return a;
}
}
}
\ No newline at end of file
......@@ -2,7 +2,6 @@ using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using PhoneStore.Enums;
using PhoneStore.Models;
using PhoneStore.Services.Interfaces;
......
......@@ -4,7 +4,7 @@ using PhoneStore.Models;
namespace PhoneStore.Services
{
public class AdminInitializerService
public static class AdminInitializerService
{
public static async Task SeedAdminUser(
RoleManager<Role> roleManager,
......
......@@ -31,6 +31,7 @@ namespace PhoneStore.Services
{
return _context.Baskets
.Include(b => b.Phone)
.ThenInclude(p => p.Brand)
.ToList();
}
......
using System;
using System.Linq;
using System.Security.Claims;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using PhoneStore.Helpers;
using PhoneStore.Mappers;
using PhoneStore.Models;
using PhoneStore.Repositories.Interfaces;
using PhoneStore.Services.Interfaces;
using PhoneStore.ViewModels.Feedback;
......@@ -12,19 +11,23 @@ namespace PhoneStore.Services
{
public class FeedbackService : IFeedbackService
{
private readonly MobileContext _db;
private readonly UserManager<User> _userManager;
private readonly IFeedbackRepository _feedbackRepository;
public FeedbackService(
MobileContext db,
UserManager<User> userManager)
UserManager<User> userManager,
IFeedbackRepository feedbackRepository)
{
_db = db;
_userManager = userManager;
_feedbackRepository = feedbackRepository;
}
public FeedbackViewModel Create(FeedbackCreateViewModel model, ClaimsPrincipal user)
{
var userId = int.Parse(_userManager.GetUserId(user));
var exist = _feedbackRepository.CheckFeedbackExists(userId, model.PhoneId);
if (exist)
return null;
Feedback feedback = new Feedback
{
CreationDateTime = DateTime.Now,
......@@ -32,29 +35,29 @@ namespace PhoneStore.Services
PhoneId = model.PhoneId,
UserId = int.Parse(_userManager.GetUserId(user))
};
_db.Feedbacks.Add(feedback);
_db.SaveChanges();
Feedback newFeedback = _db.Feedbacks
.Include(f => f.User)
.Include(f => f.Phone)
.First(f => f.Id == feedback.Id);
FeedbackViewModel feedbackViewModel = newFeedback.MapToFeedbackViewModel();
_feedbackRepository.Create(feedback);
FeedbackViewModel feedbackViewModel = _feedbackRepository
.GetById(feedback.Id)
.MapToFeedbackViewModel();
return feedbackViewModel;
}
public FeedbackViewModel Update(FeedbackEditViewModel model)
{
var feedback = _db.Feedbacks
.Include(f => f.User)
.Include(f => f.Phone)
.FirstOrDefault(f => f.Id == model.Id);
var feedback = _feedbackRepository.GetById(model.Id);
if (feedback is null)
return null;
feedback.Text = model.Text;
_db.Update(feedback);
_db.SaveChanges();
_feedbackRepository.Update(feedback);
return feedback.MapToFeedbackViewModel();
}
public FeedbackViewModel GetById(int id)
{
return _feedbackRepository
.GetById(id)
.MapToFeedbackViewModel();
}
}
}
\ No newline at end of file
using System.Collections.Generic;
using System.Security.Claims;
using System.Threading.Tasks;
using PhoneStore.DataObjects;
using PhoneStore.Models;
......
using System.Security.Claims;
using PhoneStore.Models;
using PhoneStore.ViewModels.Feedback;
namespace PhoneStore.Services.Interfaces
......@@ -7,5 +8,6 @@ namespace PhoneStore.Services.Interfaces
{
FeedbackViewModel Create(FeedbackCreateViewModel model, ClaimsPrincipal user);
FeedbackViewModel Update(FeedbackEditViewModel model);
FeedbackViewModel GetById(int id);
}
}
\ No newline at end of file
using System.Collections.Generic;
using PhoneStore.Models;
using PhoneStore.ViewModels;
namespace PhoneStore.Services.Interfaces
{
public interface IOrderService
{
IEnumerable<OrderViewModel> GetAll();
void Create(Order order);
OrderViewModel GetById(int id);
IEnumerable<OrderViewModel> GetByUserId(int id);
}
}
\ No newline at end of file
using PhoneStore.ViewModels;
using PhoneStore.ViewModels.PhoneViewModels;
namespace PhoneStore.Services.Interfaces
{
public interface IPhoneService : ICreatable<PhoneCreateViewModel>
{
PhoneViewModel GetPhoneById(int phoneId);
PhoneViewModel GetById(int phoneId);
}
}
\ No newline at end of file
using System.Collections.Generic;
using System.Linq;
using PhoneStore.Mappers;
using PhoneStore.Models;
using PhoneStore.Repositories.Interfaces;
using PhoneStore.Services.Interfaces;
using PhoneStore.ViewModels;
namespace PhoneStore.Services
{
public class OrderService : IOrderService
{
private readonly IOrderRepository _orderRepository;
public OrderService(IOrderRepository orderRepository)
{
_orderRepository = orderRepository;
}
public IEnumerable<OrderViewModel> GetAll()
=> _orderRepository.GetAll().Select(o => o.MapToOrderViewModel());
public void Create(Order order)
=> _orderRepository.Create(order);
public OrderViewModel GetById(int id)
=> _orderRepository.GetById(id).MapToOrderViewModel();
public IEnumerable<OrderViewModel> GetByUserId(int id)
=> _orderRepository
.GetByUserId(id)
.Select(o => o.MapToOrderViewModel());
}
}
\ No newline at end of file
......@@ -4,10 +4,10 @@ using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Hosting;
using PhoneStore.Helpers;
using PhoneStore.Mappers;
using PhoneStore.Models;
using PhoneStore.Repositories.Interfaces;
using PhoneStore.Services.Interfaces;
using PhoneStore.ViewModels;
using PhoneStore.ViewModels.Feedback;
using PhoneStore.ViewModels.PhoneViewModels;
......@@ -19,6 +19,7 @@ namespace PhoneStore.Services
private readonly IDefaultPhoneImagePathProvider _imagePathProvider;
private readonly UploadService _uploadService;
private readonly IHostEnvironment _environment;
private readonly IPhoneRepository _phoneRepository;
......@@ -26,12 +27,13 @@ namespace PhoneStore.Services
MobileContext db,
IDefaultPhoneImagePathProvider imagePathProvider,
UploadService uploadService,
IHostEnvironment environment)
IHostEnvironment environment, IPhoneRepository phoneRepository)
{
_db = db;
_imagePathProvider = imagePathProvider;
_uploadService = uploadService;
_environment = environment;
_phoneRepository = phoneRepository;
}
public async Task CreateAsync(PhoneCreateViewModel entity)
......@@ -54,6 +56,13 @@ namespace PhoneStore.Services
await _db.SaveChangesAsync();
}
public PhoneViewModel GetById(int phoneId)
{
return _phoneRepository
.GetById(phoneId)
.MapToPhoneViewModel();
}
public PhoneViewModel GetPhoneById(int phoneId)
{
var phone = _db.Phones
......
using System;
using System.Collections.Generic;
using System.Linq;
using PhoneStore.Models;
......
using System.Text;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using PhoneStore.Helpers;
using PhoneStore.Models;
using PhoneStore.Services;
namespace PhoneStore
{
......@@ -28,8 +25,12 @@ namespace PhoneStore
.AddIdentity<User, Role>()
.AddEntityFrameworkStores<MobileContext>();
services.AddControllersWithViews();
//Можно так подключать сервисы
services.AddApplicationServices(Configuration);
//А можно так
RepositoryConnector.AddRepositories(services);
services.AddValidationServices();
services.AddCors();
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
......@@ -50,6 +51,7 @@ namespace PhoneStore
app.UseStaticFiles();
app.UseRouting();
app.UseCors(builder => builder.AllowAnyOrigin());
app.UseAuthentication();
app.UseAuthorization();
app.UseEndpoints(endpoints =>
......
namespace PhoneStore.ViewModels.Account
{
public class UserViewModel
public class UserViewModel : BaseEntity
{
public int Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public string Email { get; set; }
......
namespace PhoneStore.ViewModels.Feedback
{
public class FeedbackEditViewModel
public class FeedbackEditViewModel : BaseEntity
{
public int Id { get; set; }
public string Text { get; set; }
}
}
\ No newline at end of file
......@@ -4,9 +4,8 @@ using PhoneStore.ViewModels.PhoneViewModels;
namespace PhoneStore.ViewModels.Feedback
{
public class FeedbackViewModel
public class FeedbackViewModel : BaseEntity
{
public int Id { get; set; }
public int UserId { get; set; }
public int PhoneId { get; set; }
public string Text { get; set; }
......
using Microsoft.AspNetCore.Http;
namespace PhoneStore.ViewModels
{
public class FileViewModel
{
public IFormFile File { get; set; }
}
}
\ No newline at end of file
using PhoneStore.ViewModels.Account;
using PhoneStore.ViewModels.PhoneViewModels;
namespace PhoneStore.ViewModels
{
public class OrderViewModel : BaseEntity
{
public int UserId { get; set; }
public UserViewModel User { get; set; }
public string ContactPhone { get; set; }
public string Address { get; set; }
public int PhoneId { get; set; }
public PhoneViewModel Phone { get; set; }
}
}
\ No newline at end of file
......@@ -6,9 +6,8 @@ using PhoneStore.Models;
namespace PhoneStore.ViewModels.PhoneViewModels
{
public class PhoneCreateViewModel
public class PhoneCreateViewModel : BaseEntity
{
public int Id { get; set; }
[Required(ErrorMessage = "Поле обязательно для заполнения")]
[Remote("CheckName", "PhoneValidator", ErrorMessage = "Имя занято")]
[StringLength(50, MinimumLength = 3, ErrorMessage = "Минимальная длина 3 символа, максимальная - 50")]
......
......@@ -4,13 +4,13 @@ using PhoneStore.ViewModels.Feedback;
namespace PhoneStore.ViewModels.PhoneViewModels
{
public class PhoneViewModel
public class PhoneViewModel : BaseEntity
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
public int BrandId { get; set; }
public Brand Brand { get; set; }
public string Image { get; set; }
public List<FeedbackViewModel> Feedbacks { get; set; }
public IEnumerable<FeedbackViewModel> Feedbacks { get; set; }
}
}
\ No newline at end of file
@model Order
@model OrderViewModel
@{
ViewBag.Title = "Заказать смартфон";
......@@ -12,7 +12,7 @@
<div class="form-row">
<label for="">
Имя покупателя
<input asp-for="UserName" type="text">
<input asp-for="@Model.User.Name" type="text">
</label>
</div>
<div class="form-row">
......
@model List<Order>
@model IEnumerable<OrderViewModel>
@{
ViewBag.Title = "Список заказов";
Layout = "_Layout";
}
@if (Model.Count == 0)
@if (!Model.Any())
{
<h2>Список пуст</h2>
}
......@@ -25,7 +25,7 @@ else
<td>@order.Id</td>
<td>@order.Address</td>
<td>@order.ContactPhone</td>
<td>@order.UserName</td>
<td>@order.User.Name</td>
<td>@order.Phone.Name</td>
</tr>
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment