شروع به کار با EF Core 1.0 - قسمت 14 - لایه بندی و تزریق وابستگیها
نویسنده: وحید نصیری
تاریخ: ۱۳۹۵/۰۶/۱۵ ۱۴:۲۰
آدرس: www.dntips.ir
| مطالب | ۳۶۹۴ |
| نویسندگان | ۲۷۶ |
| گروههای مطالب | ۱۰۲۴ |
| نقشههای راه | ۱۱۹ |
| دورهها | ۱۴ |
| اشتراکها | ۱۷۹۱۴ |
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<ApplicationDbContext>(ServiceLifetime.Scoped); public class TestDBController : Controller
{
private readonly ApplicationDbContext _ctx;
public TestDBController(ApplicationDbContext ctx)
{
_ctx = ctx;
}
public IActionResult Index()
{
var name = _ctx.Persons.First().FirstName;
return Json(new { firstName = name });
}
} public class ApplicationDbContext : IUnitOfWork
public interface IUnitOfWork : IDisposable
{
DbSet<TEntity> Set<TEntity>() where TEntity : class;
void AddRange<TEntity>(IEnumerable<TEntity> entities) where TEntity : class;
void RemoveRange<TEntity>(IEnumerable<TEntity> entities) where TEntity : class;
EntityEntry<TEntity> Entry<TEntity>(TEntity entity) where TEntity : class;
void MarkAsChanged<TEntity>(TEntity entity) where TEntity : class;
void ExecuteSqlCommand(string query);
void ExecuteSqlCommand(string query, params object[] parameters);
int SaveAllChanges();
Task<int> SaveAllChangesAsync();
} public abstract class DbSet<TEntity> : IQueryable<TEntity>, IEnumerable<TEntity>, IEnumerable, IQueryable, IAsyncEnumerableAccessor<TEntity>, IInfrastructure<IServiceProvider> where TEntity : class
public class ApplicationDbContext : DbContext, IUnitOfWork
{
private readonly IConfigurationRoot _configuration;
public ApplicationDbContext(IConfigurationRoot configuration)
{
_configuration = configuration;
}
//public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options) : base(options)
//{
//}
public virtual DbSet<Blog> Blog { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlServer(
_configuration["ConnectionStrings:ApplicationDbContextConnection"]
, serverDbContextOptionsBuilder =>
{
var minutes = (int)TimeSpan.FromMinutes(3).TotalSeconds;
serverDbContextOptionsBuilder.CommandTimeout(minutes);
}
);
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
}
public void AddRange<TEntity>(IEnumerable<TEntity> entities) where TEntity : class
{
base.Set<TEntity>().AddRange(entities);
}
public void RemoveRange<TEntity>(IEnumerable<TEntity> entities) where TEntity : class
{
base.Set<TEntity>().RemoveRange(entities);
}
public void MarkAsChanged<TEntity>(TEntity entity) where TEntity : class
{
base.Entry(entity).State = EntityState.Modified; // Or use ---> this.Update(entity);
}
public void ExecuteSqlCommand(string query)
{
base.Database.ExecuteSqlCommand(query);
}
public void ExecuteSqlCommand(string query, params object[] parameters)
{
base.Database.ExecuteSqlCommand(query, parameters);
}
public int SaveAllChanges()
{
return base.SaveChanges();
}
public Task<int> SaveAllChangesAsync()
{
return base.SaveChangesAsync();
}
} public class ApplicationDbContext : DbContext, IUnitOfWork
public interface IUnitOfWork : IDisposable
public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IConfigurationRoot>(provider => { return Configuration; });
services.AddDbContext<ApplicationDbContext>(ServiceLifetime.Scoped);
services.AddScoped<IUnitOfWork, ApplicationDbContext>(); {
"version": "1.0.0-*",
"dependencies": {
"Core1RtmEmptyTest.DataLayer": "1.0.0-*",
"Core1RtmEmptyTest.Entities": "1.0.0-*",
"Core1RtmEmptyTest.ViewModels": "1.0.0-*",
"Microsoft.Extensions.Configuration.Abstractions": "1.0.0",
"Microsoft.Extensions.Options": "1.0.0",
"NETStandard.Library": "1.6.0"
},
"frameworks": {
"netstandard1.6": {
"imports": "dnxcore50"
}
}
} namespace Core1RtmEmptyTest.Services
{
public interface IBlogService
{
IReadOnlyList<Blog> GetPagedBlogsAsNoTracking(int pageNumber, int recordsPerPage);
}
public class BlogService : IBlogService
{
private readonly IUnitOfWork _uow;
private readonly DbSet<Blog> _blogs;
public BlogService(IUnitOfWork uow)
{
_uow = uow;
_blogs = _uow.Set<Blog>();
}
public IReadOnlyList<Blog> GetPagedBlogsAsNoTracking(int pageNumber, int recordsPerPage)
{
var skipRecords = pageNumber * recordsPerPage;
return _blogs
.AsNoTracking()
.Skip(skipRecords)
.Take(recordsPerPage)
.ToList();
}
}
} public void ConfigureServices(IServiceCollection services)
{
services.AddSingleton<IConfigurationRoot>(provider => { return Configuration; });
services.AddDbContext<ApplicationDbContext>(ServiceLifetime.Scoped);
services.AddScoped<IUnitOfWork, ApplicationDbContext>();
services.AddScoped<IBlogService, BlogService>(); public class TestDBController : Controller
{
private readonly IBlogService _blogService;
private readonly IUnitOfWork _uow;
public TestDBController(IBlogService blogService, IUnitOfWork uow)
{
_blogService = blogService;
_uow = uow;
} _unitofwork.MarkAsChanged(entity);
An unhandled exception has occurred while executing the request System.InvalidOperationException: The instance of entity type 'Country' cannot be tracked because another instance of this type with the same key is already being tracked. When adding new entities, for most key types a unique temporary key value will be created if no key is set (i.e. if the key property is assigned the default value for its type). If you are explicitly setting key values for new entities, ensure they do not collide with existing entities or temporary values generated for other new entities. When attaching existing entities, ensure that only one entity instance with a given key value is attached to the context.
services.AddScoped<IUnitOfWork, ApplicationDbContext>();
Cannot create a ModificationFunction for an entity in state 'Unchanged'.
_un.ExecuteSqlCommand("Update command"); _blogService.SqlCmd("update command "); protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder
.UseSqlServer(
@"Server=(localdb)\mssqllocaldb;Database=EFMiscellanous.ConnectionResiliency;Trusted_Connection=True;ConnectRetryCount=0",
options => options.EnableRetryOnFailure());
} _blogs = _uow.Set<Blog>();
public BlogService(IUnitOfWork uow)
{
_uow = uow;
_blogs = _uow.Set<Blog>();
} An unhandled exception occurred while processing the request. InvalidOperationException: Unable to resolve service for type 'Microsoft.Extensions.Configuration.IConfigurationRoot' while attempting to activate 'OnionArchitecture.Data.ApplicationDbContext'. Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteFactory.CreateArgumentCallSites(Type serviceType, Type implementationType, CallSiteChain callSiteChain, ParameterInfo[] parameters, bool throwIfCallSiteNotFound)
public interface IBlogService
{
IReadOnlyList<Blog> GetPagedBlogsAsNoTracking(int pageNumber, int recordsPerPage);
}
public class BlogService : IBlogService
{
private readonly IUnitOfWork _uow;
private readonly DbSet<Blog> _blogs;
public BlogService(IUnitOfWork uow)
{
_uow = uow;
_blogs = _uow.Set<Blog>();
}
public IReadOnlyList<Blog> GetPagedBlogsAsNoTracking(int pageNumber, int recordsPerPage)
{
var skipRecords = pageNumber * recordsPerPage;
return _blogs
.AsNoTracking()
.Skip(skipRecords)
.Take(recordsPerPage)
.ToList();
}
} public class BlogService : IBlogService
{
private readonly IUnitOfWork _uow;
private readonly DbSet<Blog> _blogs;
private readonly AppDbContext _ctx;
public BlogService(IUnitOfWork uow, AppDbContext ctx)
{
_uow = uow;
_blogs = _uow.Set<Blog>();
_ctx = ctx
}
public IReadOnlyList<Blog> GetBlogWithTerm(string search)
{
var list = _ctx.Posts.Where(p => p.Title.Contains("test title")))
.ToList();
}
} using Common.GuardToolkit;
using Entities;
using Microsoft.AspNetCore.Mvc;
using Services.Contracts;
using ViewModels;
namespace web.Controllers
{
public class ProductController : Controller
{
private readonly IProductService _ProductService;
public ProductController(IProductService ProductService)
{
_ProductService = ProductService;
_ProductService.CheckArgumentIsNull(nameof(ProductService));
}
public IActionResult Add()
{
return View("ProductAdd");
}
[HttpPost]
public IActionResult Add(ProductAddModel model)
{
var product = new Product() { Name = model.Title, Price = 1, CategoryId = 1};
_ProductService.AddNewProduct(product);
return Json(model);
}
}
}
2. اگر بخوام برای یک منظور، تاریخ (فقط تاریخ، بدون زمان) رو نگهداری کنم ، توصیه شما برای نوع داده ای پایگاه داده، و نیز روش درست ذخیره و بازیابی چی هست؟
متشکرم