Blazor 5x - قسمت 13 - کار با فرمها - بخش 1 - کار با EF Core در برنامههای Blazor Server
نویسنده: وحید نصیری
تاریخ: ۱۳۹۹/۱۲/۱۹ ۱۵:۳۵
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
dotnet tool update -g Microsoft.Web.LibraryManager.Cli libman init libman install bootstrap --provider unpkg --destination wwwroot/lib/bootstrap libman install open-iconic --provider unpkg --destination wwwroot/lib/open-iconic
@import url('open-iconic/font/css/open-iconic-bootstrap.min.css'); <head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>BlazorServer.App</title>
<base href="~/" />
<link href="lib/open-iconic/font/css/open-iconic-bootstrap.min.css" rel="stylesheet" />
<link href="lib/bootstrap/dist/css/bootstrap.min.css" rel="stylesheet" />
<link href="css/site.css" rel="stylesheet" />
<link href="BlazorServer.App.styles.css" rel="stylesheet" />
</head> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
</Project> using System;
using System.ComponentModel.DataAnnotations;
namespace BlazorServer.Entities
{
public class HotelRoom
{
[Key]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public int Occupancy { get; set; }
[Required]
public decimal RegularRate { get; set; }
public string Details { get; set; }
public string SqFt { get; set; }
public string CreatedBy { get; set; }
public DateTime CreatedDate { get; set; } = DateTime.Now;
public string UpdatedBy { get; set; }
public DateTime UpdatedDate { get; set; }
}
} <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\BlazorServer.Entities\BlazorServer.Entities.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
</Project> using BlazorServer.Entities;
using Microsoft.EntityFrameworkCore;
namespace BlazorServer.DataAccess
{
public class ApplicationDbContext : DbContext
{
public DbSet<HotelRoom> HotelRooms { get; set; }
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
{ }
}
} <Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\BlazorServer.DataAccess\BlazorServer.DataAccess.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="5.0.3" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.3">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
</ItemGroup>
</Project> namespace BlazorServer.App
{
public class Startup
{
// ...
public void ConfigureServices(IServiceCollection services)
{
var connectionString = Configuration.GetConnectionString("DefaultConnection");
services.AddDbContext<ApplicationDbContext>(options => options.UseSqlServer(connectionString));
// ... {
"ConnectionStrings": {
"DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=HotelManagement;Trusted_Connection=True;MultipleActiveResultSets=true"
}
} dotnet tool update --global dotnet-ef --version 5.0.3 dotnet build dotnet ef migrations --startup-project ../BlazorServer.App/ add Init --context ApplicationDbContext dotnet ef --startup-project ../BlazorServer.App/ database update --context ApplicationDbContext
using System;
using System.ComponentModel.DataAnnotations;
namespace BlazorServer.Models
{
public record HotelRoomDTO
{
public int Id { get; init; }
[Required(ErrorMessage = "Please enter the room's name")]
public string Name { get; init; }
[Required(ErrorMessage = "Please enter the occupancy")]
public int Occupancy { get; init; }
[Range(1, 3000, ErrorMessage = "Regular rate must be between 1 and 3000")]
public decimal RegularRate { get; init; }
public string Details { get; init; }
public string SqFt { get; init; }
}
} <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<ProjectReference Include="..\BlazorServer.Entities\BlazorServer.Entities.csproj" />
<ProjectReference Include="..\BlazorServer.Models\BlazorServer.Models.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="8.1.1" />
</ItemGroup>
</Project> using AutoMapper;
using BlazorServer.Entities;
namespace BlazorServer.Models.Mappings
{
public class MappingProfile : Profile
{
public MappingProfile()
{
CreateMap<HotelRoomDTO, HotelRoom>().ReverseMap(); // two-way mapping
}
}
} namespace BlazorServer.App
{
public class Startup
{
// ...
public void ConfigureServices(IServiceCollection services)
{
services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
// ... using System.Collections.Generic;
using System.Threading.Tasks;
using BlazorServer.Models;
namespace BlazorServer.Services
{
public interface IHotelRoomService
{
Task<HotelRoomDTO> CreateHotelRoomAsync(HotelRoomDTO hotelRoomDTO);
Task<int> DeleteHotelRoomAsync(int roomId);
IAsyncEnumerable<HotelRoomDTO> GetAllHotelRoomsAsync();
Task<HotelRoomDTO> GetHotelRoomAsync(int roomId);
Task<HotelRoomDTO> IsRoomUniqueAsync(string name);
Task<HotelRoomDTO> UpdateHotelRoomAsync(int roomId, HotelRoomDTO hotelRoomDTO);
}
} using System;
using System.Collections.Generic;
using System.Threading.Tasks;
using AutoMapper;
using AutoMapper.QueryableExtensions;
using BlazorServer.DataAccess;
using BlazorServer.Entities;
using BlazorServer.Models;
using Microsoft.EntityFrameworkCore;
namespace BlazorServer.Services
{
public class HotelRoomService : IHotelRoomService
{
private readonly ApplicationDbContext _dbContext;
private readonly IMapper _mapper;
private readonly IConfigurationProvider _mapperConfiguration;
public HotelRoomService(ApplicationDbContext dbContext, IMapper mapper)
{
_dbContext = dbContext ?? throw new ArgumentNullException(nameof(dbContext));
_mapper = mapper ?? throw new ArgumentNullException(nameof(mapper));
_mapperConfiguration = mapper.ConfigurationProvider;
}
public async Task<HotelRoomDTO> CreateHotelRoomAsync(HotelRoomDTO hotelRoomDTO)
{
var hotelRoom = _mapper.Map<HotelRoom>(hotelRoomDTO);
hotelRoom.CreatedDate = DateTime.Now;
hotelRoom.CreatedBy = "";
var addedHotelRoom = await _dbContext.HotelRooms.AddAsync(hotelRoom);
await _dbContext.SaveChangesAsync();
return _mapper.Map<HotelRoomDTO>(addedHotelRoom.Entity);
}
public async Task<int> DeleteHotelRoomAsync(int roomId)
{
var roomDetails = await _dbContext.HotelRooms.FindAsync(roomId);
if (roomDetails == null)
{
return 0;
}
_dbContext.HotelRooms.Remove(roomDetails);
return await _dbContext.SaveChangesAsync();
}
public IAsyncEnumerable<HotelRoomDTO> GetAllHotelRoomsAsync()
{
return _dbContext.HotelRooms
.ProjectTo<HotelRoomDTO>(_mapperConfiguration)
.AsAsyncEnumerable();
}
public Task<HotelRoomDTO> GetHotelRoomAsync(int roomId)
{
return _dbContext.HotelRooms
.ProjectTo<HotelRoomDTO>(_mapperConfiguration)
.FirstOrDefaultAsync(x => x.Id == roomId);
}
public Task<HotelRoomDTO> IsRoomUniqueAsync(string name)
{
return _dbContext.HotelRooms
.ProjectTo<HotelRoomDTO>(_mapperConfiguration)
.FirstOrDefaultAsync(x => x.Name == name);
}
public async Task<HotelRoomDTO> UpdateHotelRoomAsync(int roomId, HotelRoomDTO hotelRoomDTO)
{
if (roomId != hotelRoomDTO.Id)
{
return null;
}
var roomDetails = await _dbContext.HotelRooms.FindAsync(roomId);
var room = _mapper.Map(hotelRoomDTO, roomDetails);
room.UpdatedBy = "";
room.UpdatedDate = DateTime.Now;
var updatedRoom = _dbContext.HotelRooms.Update(room);
await _dbContext.SaveChangesAsync();
return _mapper.Map<HotelRoomDTO>(updatedRoom.Entity);
}
}
} namespace BlazorServer.App
{
public class Startup
{
// ...
public void ConfigureServices(IServiceCollection services)
{
services.AddScoped<IHotelRoomService, HotelRoomService>();
// ... services.AddAutoMapper(AppDomain.CurrentDomain.GetAssemblies());
services.AddAutoMapper(typeof(MappingProfile).Assembly);
dotnet new webapi -o WebService
dotnet sln add WebService/WebService.csproj
dotnet add Web/Web.csproj reference DataLayer/DataLayer.csproj
cd YourFolder
dotnet add package Microsoft.EntityFrameworkCore.Design
dotnet tool update --global dotnet-ef dotnet ef migrations --startup-project WebService/ add Init -p DataLayer --context SqlServerContext dotnet ef --startup-project WebService/ database update Init -p DataLayer --context SqlServerContext
if (roomId != hotelRoomDTO.Id)
{
return null;
}