(倉庫モード)ASP.NET Core用EF Core用はMicrosoft.EntityFrameworkCore.SqlServer 2.0.3バージョン

13339 ワード

方法1:
using MatrixWebApiCore.Entity;
using Microsoft.EntityFrameworkCore;
using System; 
using System.Linq; 

namespace MatrixWebApiCore.Common.Data
{
    public class DataContext : DbContext
    {

        public DataContext(DbContextOptions options)
      : base(options)
        { }
 
        /// 
        ///     ,       
        /// 
        public virtual DbSet GroupCharts { get; set; }
        public virtual DbSet CombinationGroupCharts { get; set; }
        /// 
        ///     
        /// 
        public virtual DbSet Log { get; set; }        
    }   
}

using MatrixWebApiCore.Entity;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Linq.Expressions;

namespace MatrixWebApiCore.Common.Data
{
    public class RepositoryBase : IRepository where T : BaseEntity, new()
    {
        private DataContext dbContext;
        private DbSet dbSet;
        public RepositoryBase(DataContext _dbContext)
        {
            dbContext = _dbContext;
            dbSet = dbContext.Set();
        } 

        public int Add(T entity)
        {
            dbSet.Add(entity);
            return dbContext.SaveChanges();
        }

        public int Add(IEnumerable entitys)
        {
            foreach (var entity in entitys)
            {
                dbSet.Add(entity);
            }
            return dbContext.SaveChanges();
        }

        public int Update(T entity)
        {
            dbSet.Attach(entity);
            dbContext.Entry(entity).State = EntityState.Modified;
            return dbContext.SaveChanges();
        }

        public int Update(IEnumerable entitys)
        {
            foreach (var entity in entitys)
            {
                dbSet.Attach(entity);
                dbContext.Entry(entity).State = EntityState.Modified;
            }
            return dbContext.SaveChanges();
        }

        public int Delete(T entity)
        {
            dbSet.Attach(entity);
            dbSet.Remove(entity);
            return dbContext.SaveChanges();
        }
       

        public int Delete(Expression> where)
        {
            var entitys = this.GetList(where);
            foreach (var entity in entitys)
            {
                dbSet.Remove(entity);
            }
            return dbContext.SaveChanges();
        }
        public T Get(Expression> where)
        {
            return dbSet.Where(where).FirstOrDefault();
        }

        public IQueryable GetList(Expression> where)
        {
            return dbSet.Where(where);
        }

        public IQueryable GetQuery()
        {
            return dbSet;
        }

        public IQueryable GetQuery(Expression> where)
        {
            return dbSet.Where(where);
        }
   
        public IQueryable GetAll()
        {
            return dbSet.AsParallel().AsQueryable();
            //return dbSet.AsQueryable();
        }

        public T GetAsNoTracking(Expression> where)
        {
            return dbSet.Where(where).AsNoTracking().FirstOrDefault();
        }

        public IQueryable GetManyAsNoTracking(Expression> where)
        {
            return dbSet.AsNoTracking().Where(where);
        }

        public IQueryable GetAllAsNoTracking()
        {
            return dbSet.AsNoTracking();
        }

        public bool Any(Expression> @where)
        {
            return dbSet.Any(where);
        }

        public int Count(Expression> @where)
        {
            return dbSet.Count(where);
        }
       

    }
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace MatrixWebApiCore.Common.Data
{

    public interface IRepository where T : class
    {   
        int Add(T entity);
        int Add(IEnumerable entitys);
        int Update(T entity);
        int Delete(T entity);       
        int Delete(Expression> where);
        T Get(Expression> where);
        IQueryable GetList(Expression> where);
        IQueryable GetQuery(); 
        IQueryable GetQuery(Expression> where);        
        IQueryable GetAll();
        T GetAsNoTracking(Expression> where);
        IQueryable GetManyAsNoTracking(Expression> where);       
        IQueryable GetAllAsNoTracking();

        /// 
        ///       
        /// 
        /// 
        /// 
        bool Any(Expression> where);
        int Count(Expression> where);
 
    }
}

public interface IGroupChartsRepository :  IRepository
{ 
}

public class GroupChartsRepository : RepositoryBase, IGroupChartsRepository
{
	public GroupChartsRepository(DataContext db) : base(db)
	{ }
}


[Produces("application/json")]
[Route("api/[controller]")]
public class ChartDataController : Controller
{
	private IGroupChartsRepository _group;

	public ChartDataController(IGroupChartsRepository group)
	{
		_group = group;		 
	}
	
    [HttpPost("Delete")]
	public async Task DeleteSavedReport([FromBody]BaseRequest parames)
	{
	  return await Task.Run(() =>
		{
			_group.Delete(w => w.Id == parames.Guid);
		}
	}
	
}	





スタータープでcs登録サービス

public void ConfigureServices(IServiceCollection services)
{
	string sqlConnection ="     ";
	services.AddDbContext(option => option.UseSqlServer(sqlConnection));

	services.AddScoped();	
	//services.AddScoped(); 
	//services.AddSingleton();
	services.BuildServiceProvider();          

	//    
	services.AddCors();
	//      
	services.AddMemoryCache();
	//services.AddResponseCaching();
	services.AddMvcCore(options =>
	{
	//       
	options.Filters.Add();
	//options.CacheProfiles.Add("test1", new CacheProfile());
	})
	//services.AddMvc()
	.AddJsonFormatters()//    json    ,     
	.AddApiExplorer()
	//    Json     
	.AddJsonOptions(options =>
	{
		//      
		options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
		//        key
		options.SerializerSettings.ContractResolver = new DefaultContractResolver();
		//      
		options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
	});
}

方式2 DataContextには違いがあり、Repositoryには違いがあり、それからStartupである.csにはこの行のコードを書く必要はありません.
services.AddDbContext(option => option.UseSqlServer(sqlConnection));

他の書き方は上記とそっくりですが、この登録サービスは次のように書きます.
services.AddScoped();
using MatrixWebApiCore.Entity;
using Microsoft.EntityFrameworkCore;
using System; 
using System.Linq; 

namespace MatrixWebApiCore.Common.Data
{
    public class DataContext : DbContext
    {  

        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            optionsBuilder.UseSqlServer("     ");
            //optionsBuilder.UseSqlServer(@"Server=(localdb)\mssqllocaldb;Database=Blogging;Trusted_Connection=True;");
        }

        /// 
        ///     ,       
        /// 
        public virtual DbSet GroupCharts { get; set; }
        public virtual DbSet CombinationGroupCharts { get; set; }
        /// 
        ///     
        /// 
        public virtual DbSet Log { get; set; }        
    }   
}

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace MatrixWebApiCore.Common.Data
{

    public interface IRepository where T : class
    {
        DataContext GetDataContext { get; }
        int Add(T entity);
        int Add(IEnumerable entitys);
        int Update(T entity);
        int Delete(T entity);       
        int Delete(Expression> where);
        T Get(Expression> where);
        IQueryable GetList(Expression> where);
        IQueryable GetQuery(); 
        IQueryable GetQuery(Expression> where);        
        IQueryable GetAll();
        T GetAsNoTracking(Expression> where);
        IQueryable GetManyAsNoTracking(Expression> where);       
        IQueryable GetAllAsNoTracking();

        /// 
        ///       
        /// 
        /// 
        /// 
        bool Any(Expression> where);
        int Count(Expression> where);
 
    }
}

using MatrixWebApiCore.Entity;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Linq.Expressions;

namespace MatrixWebApiCore.Common.Data
{
    public class RepositoryBase : IRepository where T : BaseEntity, new()
    { 
        private DataContext dbContext;
        private DbSet dbSet;

        public DataContext GetDataContext { get { return dbContext; } }

        public RepositoryBase()
        {
            dbContext = new DataContext();
            dbSet = dbContext.Set();
        }

        public int Add(T entity)
        {
            dbSet.Add(entity);
            return dbContext.SaveChanges();
        }

        public int Add(IEnumerable entitys)
        {
            foreach (var entity in entitys)
            {
                dbSet.Add(entity);
            }
            return dbContext.SaveChanges();
        }

        public int Update(T entity)
        {
            dbSet.Attach(entity);
            dbContext.Entry(entity).State = EntityState.Modified;
            return dbContext.SaveChanges();
        }

        public int Update(IEnumerable entitys)
        {
            foreach (var entity in entitys)
            {
                dbSet.Attach(entity);
                dbContext.Entry(entity).State = EntityState.Modified;
            }
            return dbContext.SaveChanges();
        }

        public int Delete(T entity)
        {
            dbSet.Attach(entity);
            dbSet.Remove(entity);
            return dbContext.SaveChanges();
        }
 

        public int Delete(Expression> where)
        {
            var entitys = this.GetList(where);
            foreach (var entity in entitys)
            {
                dbSet.Remove(entity);
            }
            return dbContext.SaveChanges();
        }
        public T Get(Expression> where)
        {
            return dbSet.Where(where).FirstOrDefault();
        }

        public IQueryable GetList(Expression> where)
        {
            return dbSet.Where(where);
        }

        public IQueryable GetQuery()
        {
            return dbSet;
        }

        public IQueryable GetQuery(Expression> where)
        {
            return dbSet.Where(where);
        }
    
        public IQueryable GetAll()
        {
            return dbSet.AsParallel().AsQueryable();
            //return dbSet.AsQueryable();
        }

        public T GetAsNoTracking(Expression> where)
        {
            return dbSet.Where(where).AsNoTracking().FirstOrDefault();
        }

        public IQueryable GetManyAsNoTracking(Expression> where)
        {
            return dbSet.AsNoTracking().Where(where);
        }

        public IQueryable GetAllAsNoTracking()
        {
            return dbSet.AsNoTracking();
        }

        public bool Any(Expression> @where)
        {
            return dbSet.Any(where);
        }

        public int Count(Expression> @where)
        {
            return dbSet.Count(where);
        }

    }
}

public class GroupChartsRepository : RepositoryBase, IGroupChartsRepository
{       
}