net core Webapi infrastructure construction-database operation_Part 2

Keywords: Database MySQL SQL

Preface

Yesterday was written about discovery. It's not too early. I've formed the habit of taking time off from work at night to see what I can write. Today I really don't want to be influenced by what I didn't finish yesterday. So I sat down again and settled down (over the weekend) and began to complete the database.

Yesterday, I have introduced most of the things, including method encapsulation, which is also a basic demonstration. In fact, I should first introduce this article about how to boot the encapsulated class library. But now that I have written it, I don't want to adjust it any more. Today, I will mainly talk about how to use it in practice. I need to check the specific classes. The library is available for viewing net core Webapi infrastructure construction (6) - database operation_Part 1 This is the case. (Lazy can't do it)

start

Not much gossip, Service layer started to create two new folders, an Interfaces, an Implements, and incidentally a new Common folder, put the three classes in the previous article (purely for viewing, categorizing, not affecting use).


In the last article, we created a Student Entity object, which can be visited by friends who have forgotten it.
Create a new IStudentService interface and inherit IBaseService

    public interface IStudentService : IBaseService<StudentEntity>
    {
    }

Create a new StudentService implementation class, inherit BaseService and implement IStudentService

    public class StudentService : BaseService<StudentEntity>, IStudentService
    {
    }

Okay, that's it. Go home and sleep.

Use

If you see the above go directly, I'm sorry, entertainment, do not dare to learn to build a house like a crow, did not listen to their mother, I will not tell stories.

We need to associate interfaces with implementations here in StartUp. Some blogs will introduce automatic associations for decoupling, and Baidu itself if necessary.

It seems that I forgot to introduce Service and Entity in WebApi project yesterday. I'm sorry to add that.

Here, I create a new Depends folder and a new Service Injection class under Service Project Common, which unifies the relationship between interface and implementation.

    public class ServiceInjection
    {
        public static void ConfigureRepository(IServiceCollection services)
        {
            services.AddSingleton<IStudentService, StudentService>();
        }
    }

For Dependency Injection, here are a few short interludes, and new feelings will be added later.

Method Explain
Transient Each call creates a new instance
Scoped Instantiate only one in a scope
Singleton Only one instance is created throughout the application lifecycle

Then we add this sentence to the front of ConfigureServices in StartUp, which is added to the constructor for the purpose of taking over configuration information by AprilConfig.

		public Startup(IConfiguration configuration)
        {
			...Previous stuff
            AprilConfig.InitConfig(configuration);
        }
		
        public void ConfigureServices(IServiceCollection services)
        {
            ServiceInjection.ConfigureRepository(services);
            
			...Previous stuff
		}

Of course, there should be a receiving method.

    public class AprilConfig
    {
        public static IServiceProvider ServiceProvider;
        public static IConfiguration Configuration;

        public static void InitConfig(IConfiguration _configuration)
        {
            Configuration = _configuration;
        }
	}

Well, after all is written, let's continue to experiment with the evil Values controller (what a good object to open a knife).

Before that, make sure what kind of database you have. Press 1 for Sql Server, 0 for MySql, and check the documents for yourself.

In order to facilitate the unified management of the project, we need to make good use of appsettings, just as we used web.config at that time, the connection string itself is modified according to the actual situation.

  //Add a new one
  "DefaultSqlConnectionString": {
    "MySql": "server=127.0.0.1;userid=root;password=root;database=test;"
  }

In our Util layer, AprilConfig, to get the parameters.

        private static string _MySqlConnectionString = string.Empty;
        /// <summary>
        /// MySql default connection string
        /// </summary>
        public static string MySqlConnectionString
        {
            get
            {
                if (string.IsNullOrEmpty(_MySqlConnectionString))
                {
                    _MySqlConnectionString = Configuration["DefaultSqlConnectionString:MySql"];
                }
                return _MySqlConnectionString;
            }
        }

Then we will modify the connection string information left by BaseService.

Create a table structure, which is not to say that you have to create it. After all, SqlSugar has CodeFirst (and DbFirst, of course). Friends who need it can go to the document to see it. It is also relatively simple. It is also possible to judge whether there are tables when the program is started, or to make an interface to initialize it. The following figure is a brief introduction of the usage of SqlSugar. It's better to check the documents, after all, there are backups and renaming.

Everything's OK. Values, a thousand-knife East Wind, constructor to get the IStudentService interface.

    public class ValuesController : ControllerBase
    {

        private readonly IStudentService _service;

        public ValuesController(IStudentService service)
        {
            _service = service;
        }
    }
  • insert
        [HttpGet]
        public ActionResult<IEnumerable<string>> Get()
        {
            StudentEntity entity = new StudentEntity();
            entity.Name = "Xiaoming";
            entity.Age = 18;
            entity.Number = "007";
            entity.Sex = 0;
            entity.Address = "Daluoyang";
            _service.Insert(entity);
            return new string[] { "value1", "value2" };
        }

  • modify
    The SqlFilterEntity method is also illustrated here, and it extends the method of the lower entity for easy use.

SqlFilterEntity Extension Method

		//... Previous entity objects
		
		/// <summary>
        /// Adding query conditions
        /// </summary>
        /// <param name="filter">condition </param>
        /// <param name="relation">relation</param>
        public void Append(string filter, string relation = "and")
        {
            if (string.IsNullOrEmpty(filter))
            {
                return;
            }
            if (Filter.Length > 0)
            {
                Filter += relation;
            }
            Filter += filter;
        }
        /// <summary>
        /// Add query parameters
        /// </summary>
        /// <param name="key">key</param>
        /// <param name="value">value</param>
        public void Add(string key, object value)
        {
            if (string.IsNullOrEmpty(key) || value == null)
            {
                return;
            }
            if (Value == null)
            {
                Value = new Dictionary<string, object>();
            }
            if (Value.ContainsKey(key))
            {
                Value[key] = value;
            }
            else
            {
                Value.Add(key, value);
            }
        }

Modify the test

			StudentEntity entity = null;
            SqlFilterEntity filter = new SqlFilterEntity();
            filter.Append($"ID=@ID");
            filter.Add("@ID", 1);
            entity = _service.GetEntity(filter);
            if (entity != null)
            {
                entity.Name = "I've been modified.";
                _service.Update(entity);
            }
	

  • delete
    To delete this is to change the method of modification.

  • See

Paging tests are done directly here, with the interface Values/{id} as an experiment.

        [HttpGet("{id}")]
        public ActionResult<string> Get(int id)
        {
            string value = string.Empty;
            //value = CacheUtil.Get<string>("cachetest");
            //value = SessionUtil.GetSession("test");
            //value = CookieUtil.GetCookies("apirlcookietest");

            int count = 0;
            List<StudentEntity> lists = _service.GetPageList(id, 10, "", null, "", out count);

            value = JsonConvert.SerializeObject(lists);

            return value;
        }

Summary

Here is a general introduction of SqlSugar's usage, which has some basic encapsulation that can't be based on. In practice, it certainly needs to be expanded and perfected. But as a tutorial, I can't take all the situations into account. After all, business is different, there is no universal oil, only continuous improvement and updating, business scenarios are more. The function is perfected. Step by step, you can't be a fat person by one mouthful (this fat person is not the fat person you know), but you still lament that these open source libraries are really convenient for developers. In order to liberate the hands of the program ape (yy), you have made a great contribution. Okay, get back to the topic, next article. Aop testing and little things.

Posted by saurabhdutta on Fri, 19 Jul 2019 03:12:41 -0700