Язык программирования C#9 и платформа .NET5 - Троелсен Эндрю
На нашем сайте KnigaRead.com Вы можете абсолютно бесплатно читать книгу онлайн Троелсен Эндрю, "Язык программирования C#9 и платформа .NET5" бесплатно, без регистрации.
modelBuilder.Entity<CustomerOrderViewModel>(entity =>{ entity.HasNoKey().ToView("CustomerOrderView","dbo");});Добавление хранилищ
Распространенный паттерн проектирования для доступа к данным называется "Хранилище" (Repository). Согласно описанию Мартина Фаулера (
http://www.martinfowler.com/eaaCatalog/repository.htmlКаждая сущность предметной области внутри уровня доступа к данным
AutoLotAutoLot.DalReposНа заметку! Не воспринимайте следующий раздел как буквальную интерпретацию паттерна проектирования "Хранилище". Если вас интересует исходный паттерн, который послужил мотивом для создания приведенной здесь версии, тогда почитайте о нем по ссылке
http://www.martinfowler.com/eaaCatalog/repository.htmlДобавление базового интерфейса IRepo
Базовый интерфейс
IRepoAutoLot.DalReposBaseReposBaseIRepo.csusingusing System;using System.Collections.Generic;Так выглядит полный интерфейс:
namespace AutoLot.Dal.Repos.Base{ public interface IRepo<T>: IDisposable { int Add(T entity, bool persist = true); int AddRange(IEnumerable<T> entities, bool persist = true); int Update(T entity, bool persist = true); int UpdateRange(IEnumerable<T> entities, bool persist = true); int Delete(int id, byte[] timeStamp, bool persist = true); int Delete(T entity, bool persist = true); int DeleteRange(IEnumerable<T> entities, bool persist = true); T? Find(int? id); T? FindAsNoTracking(int id); T? FindIgnoreQueryFilters(int id); IEnumerable<T> GetAll(); IEnumerable<T> GetAllIgnoreQueryFilters(); void ExecuteQuery(string sql, object[] sqlParametersObjects); int SaveChanges(); }}Добавление класса BaseRepo
Добавьте в каталог
ReposBaseBaseRepo.csBaseRepoIRepousingusing System;using System.Collections.Generic;using System.Linq;using AutoLot.Dal.EfStructures;using AutoLot.Dal.Exceptions;using AutoLot.Models.Entities.Base;using Microsoft.EntityFrameworkCore;Сделайте класс обобщенным с типом
ТBaseEntitynew()IRepo<T>public abstract class BaseRepo<T> : IRepo<T> where T : BaseEntity, new()Классу хранилища нужен экземпляр
ApplicationDbContextDbContextOptionsApplicationDbContextApplicationDbContextprivate readonly bool _disposeContext;public ApplicationDbContext Context { get; }protected BaseRepo(ApplicationDbContext context){ Context = context; _disposeContext = false;}protected BaseRepo(DbContextOptions<ApplicationDbContext> options) : this(new ApplicationDbContext(options)){ _disposeContext = true;