Asp. Net MVC две таблицы - PullRequest
       0

Asp. Net MVC две таблицы

0 голосов
/ 19 июня 2020

Нужен совет. В моем проекте есть две таблицы. Таблица 1 (Лица) более статична c в том смысле, что ее не нужно изменять или обновлять, поскольку данные в основном останутся прежними.

Однако вторая таблица (инциденты) более динамична c в том смысле, что она должна иметь возможность иметь несколько записей / записей, сделанных пользователем.

Это можно сделать с помощью операций CRUD, однако часть, на которой я застрял, заключается в том, что мне нужно, чтобы пользователь мог сделать эти обновления c для индивидуальной идентификации, которая также должна соответствовать спецификациям c идентификатор первой таблицы.

Примером может быть: в приложении ищется информация о людях, а затем пользователь может создать инцидент против этого человека. Это работает, если я объединяю обе модели в одну, но тогда у меня нет возможности создать еще один инцидент для этого c человека / идентификатора, поскольку он сгенерирует другой инцидент как другой идентификатор, который вызовет проблемы, когда пользователь захочет просмотреть все инциденты, зарегистрированные против этого c человека.

Что мне нужно сделать, чтобы это работало?

Лица модели

public class Persons
{
    [Key]
    public int PersonId { get; set; }
    [Display(Name = "Service ID:")]
    public string Service_ID { get; set; }
    [Display(Name = "Rank/ Title:")]
    public string Rank { get; set; }
    [Display(Name = "Initials:")]
    public string Initials { get; set; }
    [Display(Name = "First Name:")]
    public string First_Name { get; set; }
    [Display(Name = "Middle Name:")]
    public string Middle_Name { get; set; }
    [Display(Name = "Surname:")]
    public string Surname { get; set; }
    [Display(Name = "Service:")]
    public string Service { get; set; }
    [Display(Name = "Corps:")]
    public string Corps { get; set; }
    [Display(Name = "Unit:")]
    public string Unit { get; set; }
    [Display(Name = "DOB::")]
    [DataType(DataType.Date)]
    public DateTime DOB { get; set; }
    [Display(Name = "Gender:")]
    public string Gender { get; set; }
    [Display(Name = "Address:")]
    public string Address { get; set; }
    [Display(Name = "Phone:")]
    public string Phone { get; set; }

    [Display(Name = "Plate Number:")]
    public string Vehicle_Registration { get; set; }
    [Display(Name = "Make:")]
    public string Make { get; set; }
    [Display(Name = "Model:")]
    public string Model { get; set; }
    [Display(Name = "Year:")]
    public string Year { get; set; }
    [Display(Name = "Colour:")]
    public string Colour { get; set; }
    [Display(Name = "WOF Exp:")]
    [DataType(DataType.Date)]
    public DateTime WOF { get; set; }
    [Display(Name = "REGO Exp:")]
    [DataType(DataType.Date)]
    public DateTime REGO { get; set; }

Типовые инциденты

 public class Incidents 
{
    [Key]
    public int IncidentId { get; set; }
    [Display(Name = "Event Number")]
    public string Event { get; set; }

    [Display(Name = "POC")]
    public string MP { get; set; }

    [Display(Name = "Incident/ Offence")]
    public string Incident { get; set; }
    [Display(Name = "Location of Incident")]
    public string Location { get; set; }
    [Display(Name = "Date/Time of Incident")]

    public DateTime Date_Time { get; set; }
    [Display(Name = "Role in Incident")]
    public string Role { get; set; }

    [Display(Name = "Text")]
    public string IncidentDetail { get; set; }
    [Display(Name = "BOR")]
    public string BOR { get; set; }
    [Display(Name = "Action Taken")]
    public string Action { get; set; }

Персональный контроллер

  public class PersonsController : Controller
{
    private readonly PersonsContext _context;

    public PersonsController(PersonsContext context)
    {
        _context = context;
    }

    // GET: Persons
    public async Task<IActionResult> Index(string searchstring, string searchstring1, string searchstring2, string searchstring3)
    {

        var persons = from m in _context.Persons
                      select m;


        if (!String.IsNullOrEmpty(searchstring))
        {
            persons = persons.Where(s => s.Service_ID.Contains(searchstring));

        }
        if (!String.IsNullOrEmpty(searchstring1))
        {
            persons = persons.Where(s => s.First_Name.Contains(searchstring1));

        }
        if (!String.IsNullOrEmpty(searchstring2))
        {
            persons = persons.Where(s => s.Surname.Contains(searchstring2));

        }
        if (!String.IsNullOrEmpty(searchstring3))
        {
            persons = persons.Where(s => s.Vehicle_Registration.Contains(searchstring3));

        }



        return View(await persons.ToListAsync());

    }

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

        var persons = await _context.Persons
            .FirstOrDefaultAsync(m => m.PersonId == id);
        if (persons == null)
        {
            return NotFound();
        }

        return View(persons);
    }

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

    // POST: Persons/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("Id,Service_ID,Rank,Initials,First_Name,Middle_Name,Surname,Service,Corps,Unit,DOB,Gender,Address,Phone,Vehicle_Registration,Make,Model,Year,Colour,WOF,REGO")] Persons persons)
    {
        if (ModelState.IsValid)
        {
            _context.Add(persons);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        return View(persons);
    }

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

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

    // POST: Persons/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(int id, [Bind("Id,Service_ID,Rank,Initials,First_Name,Middle_Name,Surname,Service,Corps,Unit,DOB,Gender,Address,Phone,Vehicle_Registration,Make,Model,Year,Colour,WOF,REGO")] Persons persons)
    {
        if (id != persons.PersonId)
        {
            return NotFound();
        }

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

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

        var persons = await _context.Persons
            .FirstOrDefaultAsync(m => m.PersonId == id);
        if (persons == null)
        {
            return NotFound();
        }

        return View(persons);
    }

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

    private bool PersonsExists(int id)
    {
        return _context.Persons.Any(e => e.PersonId == id);
    }
}

Контроллер инцидентов

  public class IncidentsController : Controller
{
    private readonly IncidentsContext _context;

    public IncidentsController(IncidentsContext context)
    {
        _context = context;
    }

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

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

        var incidents = await _context.Incidents
            .FirstOrDefaultAsync(m => m.IncidentId == id);
        if (incidents == null)
        {
            return NotFound();
        }

        return View(incidents);
    }

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

    // POST: Incidents/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("Id,Event,NZDFMP,Incident,Location,Date_Time,Role,IncidentDetail,BOR,Action")] Incidents incidents)
    {
        if (ModelState.IsValid)
        {
            _context.Add(incidents);
            await _context.SaveChangesAsync();
            return RedirectToAction(nameof(Index));
        }
        return View(incidents);
    }

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

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

    // POST: Incidents/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(int id, [Bind("Id,Event,NZDFMP,Incident,Location,Date_Time,Role,IncidentDetail,BOR,Action")] Incidents incidents)
    {
        if (id != incidents.IncidentId)
        {
            return NotFound();
        }

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

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

        var incidents = await _context.Incidents
            .FirstOrDefaultAsync(m => m.IncidentId == id);
        if (incidents == null)
        {
            return NotFound();
        }

        return View(incidents);
    }

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

    private bool IncidentsExists(int id)
    {
        return _context.Incidents.Any(e => e.IncidentId == id);
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...