Search code examples
postgresqlasp.net-core-mvcschema-migration

Asp.net core mvc migration database


When I add a column at Database, how to renew my DB.Context.

it is my Context.cs

 modelBuilder.Entity<SensorModbusRtusetting>(entity =>
        {
            entity.ToTable("SensorModbusRTUSetting");

            entity.Property(e => e.Id).HasColumnName("id");

            entity.Property(e => e.Baudrate).HasColumnName("baudrate");

            entity.Property(e => e.Channel)
                .IsRequired()
                .HasColumnType("jsonb")
                .HasColumnName("channel");

            entity.Property(e => e.Comport)
                .IsRequired()
                .HasColumnName("comport");

            entity.Property(e => e.Pid).HasColumnName("pid");

            entity.Property(e => e.Slaveid).HasColumnName("slaveid");

            entity.Property(e => e.Nane).HasColumnName("nane");

It is my model

    namespace Sensormanager2V2
{
    public partial class SensorModbusRtusetting
    {
        public string Comport { get; set; }
        public int Baudrate { get; set; }
        public string Channel { get; set; }
        public int Slaveid { get; set; }
        public int Pid { get; set; }
        public long Id { get; set; }
        public string Nane { get; set; }
        
    }
}

it is my controller

    using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.EntityFrameworkCore;
using Sensormanager2V2;

namespace Sensormanager2V2.Controllers
{
    public class SensorModbusRtusettingsController : Controller
    {
        private readonly postgresContext _context;

        public SensorModbusRtusettingsController(postgresContext context)
        {
            _context = context;
        }

        // GET: SensorModbusRtusettings
        public async Task<IActionResult> Index()
        {
            return View(await _context.SensorModbusRtusettings.ToListAsync());
        }

        // GET: SensorModbusRtusettings/Details/5
        public async Task<IActionResult> Details(long? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var sensorModbusRtusetting = await _context.SensorModbusRtusettings
                .FirstOrDefaultAsync(m => m.Id == id);
            if (sensorModbusRtusetting == null)
            {
                return NotFound();
            }

            return View(sensorModbusRtusetting);
        }

        // GET: SensorModbusRtusettings/Create
        public IActionResult Create()
        {
            return View();
        }

        // POST: SensorModbusRtusettings/Create
        // To protect from overposting attacks, enable the specific properties you want to bind to, for 
        // more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Create([Bind("Comport,Baudrate,Channel,Slaveid,Pid,Id,Name")] SensorModbusRtusetting sensorModbusRtusetting)
        {
            if (ModelState.IsValid)
            {
                _context.Add(sensorModbusRtusetting);
                await _context.SaveChangesAsync();
                return RedirectToAction(nameof(Index));
            }
            return View(sensorModbusRtusetting);
        }

        // GET: SensorModbusRtusettings/Edit/5
        public async Task<IActionResult> Edit(long? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var sensorModbusRtusetting = await _context.SensorModbusRtusettings.FindAsync(id);
            if (sensorModbusRtusetting == null)
            {
                return NotFound();
            }
            return View(sensorModbusRtusetting);
        }

        // POST: SensorModbusRtusettings/Edit/5
        // To protect from overposting attacks, enable the specific properties you want to bind to, for 
        // more details, see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> Edit(long id, [Bind("Comport,Baudrate,Channel,Slaveid,Pid,Id,Name")] SensorModbusRtusetting sensorModbusRtusetting)
        {
            if (id != sensorModbusRtusetting.Id)
            {
                return NotFound();
            }

            if (ModelState.IsValid)
            {
                try
                {
                    _context.Update(sensorModbusRtusetting);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!SensorModbusRtusettingExists(sensorModbusRtusetting.Id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }
                return RedirectToAction(nameof(Index));
            }
            return View(sensorModbusRtusetting);
        }

        // GET: SensorModbusRtusettings/Delete/5
        public async Task<IActionResult> Delete(long? id)
        {
            if (id == null)
            {
                return NotFound();
            }

            var sensorModbusRtusetting = await _context.SensorModbusRtusettings
                .FirstOrDefaultAsync(m => m.Id == id);
            if (sensorModbusRtusetting == null)
            {
                return NotFound();
            }

            return View(sensorModbusRtusetting);
        }

        // POST: SensorModbusRtusettings/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<IActionResult> DeleteConfirmed(long id)
        {
            var sensorModbusRtusetting = await _context.SensorModbusRtusettings.FindAsync(id);
            _context.SensorModbusRtusettings.Remove(sensorModbusRtusetting);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }

        private bool SensorModbusRtusettingExists(long id)
        {
            return _context.SensorModbusRtusettings.Any(e => e.Id == id);
        }
    }
}

Solution

  • If you update the structure of a table in your database, you need to ensure that your change is propagated to the data model, views, and controller.

    For this tutorial, you will add a new column to the Student table to record the middle name of the student. To add this column, open the database project, and open the Student.sql file. Through either the designer or the T-SQL code, add a column named MiddleName that is an NVARCHAR(50) and allows NULL values.

    Deploy this change to your local database by starting your database project (or F5). The new field is added to the table. If you do not see it in the SQL Server Object Explorer, click the Refresh button in the pane.

    enter image description here

    The new column exists in the database table, but it does not currently exist in the data model class. You must update the model to include your new column. In the Models folder, open the ContosoModel.edmx file to display the model diagram. Notice that the Student model does not contain the MiddleName property. Right-click anywhere on the design surface, and select Update Model from Database.

    In the Update Wizard, select the Refresh tab and then select Tables > dbo > Student. Click Finish.

    After the update process is finished, the database diagram includes the new MiddleName property. Save the ContosoModel.edmx file. You must save this file for the new property to be propagated to the Student.cs class. You have now updated the database and the model.

    Build the solution.