Cascade Delete for MySQL and ASP.NET MVC4 - mysql

I have create simple asp.net (MVC4) web page with mysql database. There I have two tables (persons and orders), where table orders have FORIGN Key Persons_ID. I whant to create delete function, so, when I delete person from persons table, it will also delete all orders from order table for this person.
For creating models I have used ADO.NET and it create this two models for each tables:
persons.cs
using System.ComponentModel.DataAnnotations;
namespace MvcMySQLTest1.Models
{
using System;
using System.Collections.Generic;
public partial class person
{
public person()
{
this.orders = new HashSet<order>();
}
public int ID { get; set; }
public string LastName { get; set; }
public string FirstName { get; set; }
public string Adress { get; set; }
public string City { get; set; }
public virtual ICollection<order> orders { get; set; }
}
}
orders.cs
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
namespace MvcMySQLTest1.Models
{
using System;
using System.Collections.Generic;
public partial class order
{
public int O_Id { get; set; }
public int OrderNo { get; set; }
public Nullable<int> Persons_Id { get; set; }
public virtual person person { get; set; }
}
}
I have also create MainModel - like I container for both models above:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Web;
namespace MvcMySQLTest1.Models
{
public class MainModel
{
public person Persons { get; set; }
public order Orders { get; set; }
}
}
Now for Cascade deleting I have try this - so when I delete Person, it will also delete all Orders for this Person in order table, but this seems not to work:
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using System.Linq;
using System.Web;
namespace MvcMySQLTest1.Models
{
public class MainModel : DbContext //added
{
public person Persons { get; set; }
public order Orders { get; set; }
//added
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<orders>()
.HasOptional(a => a.persons)
.WithOptionalDependent()
.WillCascadeOnDelete(true);
base.OnModelCreating(modelBuilder);
}
}
}

May be you can try something like this
modelBuilder.Entity<order>()
.HasRequired(a => a.person)
.WithMany(t => t.order)
.HasForeignKey(d => d.Persons_Id)
.WillCascadeOnDelete(true);
Or try to read more here MSDN Cascade Delete. May something can help from there

Related

crud operation with dynamic data with 3 level hierarchy in json file in asp .net core web api

I want to do get, post, put and delete in it using asp.net core Web API. But I should not use database to store the data instead I need to store the dynamic data in controller using method and also in json file list of user(userId,userName),3 level hierarchy(Country should have list of state,State should have list of city,And I could add Countries along with its states and cities) and use it to do the http action. Can any one please help me with some step or code?
I create a sample demo for you, and I suggest you don't use json file.
Why:
When you use json files, IO operations are required, and there will be a problem of exclusive use of files.
In addition, when adding, deleting, modifying and checking the content of the file, every time there is a json file that is read, then converted into an object, and then written into the file, the efficiency will be very low.
Because what you want is a demo, the test code I wrote does not have any verification. You can pay attention to the places that need attention.
AddSingleton must be used when registering a service, so as to ensure that all users access the same data source.
When the amount of data is very large and there are too many requests, there will be a situation where the data does not match. Because I have not added any locks or restrictions here.
Test Result
Test Code:
Create GlobalVariablesService, and register it
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DB_Project.Models
{
public class GlobalVariablesService
{
public List<RecordModel> records = new List<RecordModel>();
public GlobalVariablesService(){
}
public List<RecordModel> AddRecord(RecordModel r) {
records.Add(r);
return records;
}
public List<RecordModel> RemoveRecord(int rid)
{
var itemToRemove = records.Single(r => r.Record_ID == rid);
records.Remove(itemToRemove);
return records;
}
public RecordModel GetRecord(int rid)
{
var itemToGet = records.Single(r => r.Record_ID == rid);
return itemToGet;
}
}
/// <summary>
/// Add Record History
/// Rid #Uid #Country_id #Country_Name #State_id #State_Name #City_id #City_Name
/// 1 001 C1 Country1 S1 State1 C_1 City1
/// 2 002 C2 Country2 S2 State2 C_2 City2
/// 3 003 C3 Country3 S3 State3 C_3 City3
/// </summary>
///
public class RecordModel {
public int Record_ID { get; set; }
public int Uid { get; set; }
public string Country_id { set; get; }
public string Country_Name { set; get; }
public string State_id { set; get; }
public string State_Name { set; get; }
public string City_id { set; get; }
public string City_Name { set; get; }
}
public class UserModel {
public int Uid { set; get; }
public string Name { set; get; }
}
public class CountryModel
{
public string Country_id { set; get; }
public string Country_Name { set; get; }
public List<StateModel> State { set; get; }
}
public class StateModel
{
public string State_id { set; get; }
public string State_Name { set; get; }
public List<CityModel> City { set; get; }
}
public class CityModel
{
public string City_id { set; get; }
public string City_Name { set; get; }
}
}
Register service in Startup.cs file;
public void ConfigureServices(IServiceCollection services)
{
services.AddControllersWithViews();
services.AddSingleton<GlobalVariablesService>();
}
My Test Controller
using DB_Project.DbClass;
using DB_Project.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace DB_Project.Controllers
{
public class TestController : Controller
{
private readonly ILogger<TestController> _logger;
private readonly GlobalVariablesService _service;
public TestController(ILogger<TestController> logger, GlobalVariablesService service)
{
_logger = logger;
_service = service;
}
public IActionResult get(int rid)
{
try
{
var model = _service.GetRecord(rid);
return Ok(model);
}
catch (Exception e)
{
return Ok("error occured :" + e.ToString());
throw;
}
}
public string add(RecordModel r)
{//string uid,string countryid,string countryname,string stateid,string statename,string cityid,string cityname ) {
try
{
_service.AddRecord(r);
return "success";
}
catch (Exception)
{
return "failed";
throw;
}
}
public string delete(int rid){
try
{
_service.RemoveRecord(rid);
return "success";
}
catch (Exception)
{
return "failed";
throw;
}
}
}
}

Populate DropDown from database in an edit view using MVC4

I am new to MVC and trying to populate a dropdown list in the "create" view which is generated from a view model, but it returns with an error saying object reference is not an instance of an object. below is my code :
Controller Code:
public ActionResult Create()
{
return View(new AddRecipeViewModel());
}
Model Code:
public class DifficultyLevel
{
[Key]
public int Id { get; set; }
public string Difficulty { get; set; }
}
public class AddRecipeViewModel
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<RecipeReview> Reviews { get; set; }
public virtual IEnumerable<DifficultyLevel> Difficulty { get; set; }
}
View:
<div>
<select>
#foreach (var item in Model.Difficulty)
{
<option>#item.Difficulty</option>
}
</select>
</div>
Is there an easy workaround this ? as I will be adding more drop downs in this as I go along.
Thanks,
Vishal
not sure if you need to use virtual in your view models.. that's usually only for the entity models. but anyway, try adding a constructor to AddRecipeViewModel and set the collections equal to empty lists so they won't be null.
public class AddRecipeViewModel
{
public AddRecipeViewModel()
{
Reviews = new List<RecipeReview>();
Difficulty = new List<DifficultyLevel>();
}
[Key]
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<RecipeReview> Reviews { get; set; }
public virtual IEnumerable<DifficultyLevel> Difficulty { get; set; }
}

WP8 No Such a table Sqlite

i m trying to develop windows phone application but i have a problem about sqlite. I couldn't connect database and app. I had error message like this "no such table: hastalik". If some 1 have any idea, please share. Thanks for your help.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using System.IO;
using Windows.Storage;
using SQLite;
namespace illnessTracker
{
public partial class Page1 : PhoneApplicationPage
{
public static string DB_PATH = Path.Combine(Path.Combine(ApplicationData.Current.LocalFolder.Path, "ilac.sqlite"));
public Page1()
{
InitializeComponent();
}
private void ApplicationBarIconButton_Click(object sender, EventArgs e)
{
using (SQLiteConnection dbConn = new SQLiteConnection("Data Source=ilac.sqlite; FailIfMissing=True"))
{
// Create a new task.
hastalik hasta = new hastalik();
hasta.hastalikAdi = txtbxHastalikAdi.Text;
hasta.semptomlar = txtbxSemptomlar.Text;
hasta.ilaclar = tbxIlaclar.Text;
hasta.not = tbxNot.Text;
hasta.doktorTavsiyesi = tbxTavsiye.Text;
hasta.tarihi = DateTime.Now.Date;
/// Insert the new task in the Task table.
dbConn.Insert(hasta);
}
}
[Table("hastalik")]
public class hastalik
{
[Column("hastalikID")]
[PrimaryKey, AutoIncrement]
public int hastalikID { get; set; }
[Column("hastalikAdi")]
public string hastalikAdi { get; set; }
[Column("semptomlar")]
public string semptomlar { get; set; }
[Column("ilaclar")]
public string ilaclar { get; set; }
[Column("doktorTavsiyesi")]
public string doktorTavsiyesi { get; set; }
[Column("not")]
public string not { get; set; }
[Column("tarihi")]
public DateTime tarihi { get; set; }
}
}
}

Why is my code doing nothing?

When I run the debugger, I get 0 errors, the layout loads, and "Movies" shows up but literally nothing else. I'm fairly new to MVC and some input would be appreciated. The code for the View, Model, and Controller are below. The database contains over 100 items and a list a links is intended to appear but its just white space instead.
View:
#model IEnumerable<MyWebPage.Models.Movie>
<h1>Movies</h1>
<ul>
#foreach (var item in Model.OrderBy(x => x.Name))
{
<li>#Html.ActionLink(item.Name, "Movies", new { id = item.ID })</li>
}
</ul>
Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MyWebPage.Models;
namespace MyWebPage.Controllers
{
public class HomeController : Controller
{
private MoviesDbContext db = new MoviesDbContext();
public ActionResult Index()
{
return View(db.Movies.ToList());
}
public ViewResult Movies(int id)
{
Movie moviesdb = db.Movie.Find(id);
return View(moviesdb);
}
}
}
Model:
using System;
using System.Data.Entity;
namespace MyWebPage.Models
{
public class Movie
{
public int ID { get; set; }
public string Name { get; set; }
public string Cover { get; set; }
}
public class MoviesDbContext : DbContext
{
public DbSet<Movie> Movies { get; set; }
}
}
Thanks in advance!

Razor, MVC4, #html.dropdownlistfor problems

I'm trying to create a drop down list that populates from a database. I have:
public class Employee
{
[Key]
public int Id { get; set; }
[Required]
public String FirstName { get; set; }
[Required]
public String LastName { get; set; }
[Required]
public String JobTitle { get; set; }
}
public class Project
{
[Key]
public int Id { get; set; }
[Required]
public String ProjectName { get; set; }
[Required]
public String CompanyName { get; set; }
}
public class ProjectHour
{
[Key]
public int Id { get; set; }
[Required]
public decimal Hours { get; set; }
[Required]
public DateTime Date { get; set; }
public virtual ICollection<Employee> employeeId { get; set; }
public virtual ICollection<Project> projectId { get; set; }
}
What I want is to create a form that will create new project hours associated with a project and an employee. I'm trying to use dropdownlists to display the employees and the projects on the create form. Obviously, I'm completely new at this, but what I have so far is:
[HttpPost]
public ActionResult CreateProjectHour(ProjectHour newProjectHour)
{
using (var db = new TimesheetContext())
{
IEnumerable<SelectListItem> emp = db.Employees
.Select(c => new SelectListItem
{
Value = c.Id.ToString(),
Text = c.LastName
});
ViewBag.EmployeeId = emp;
db.ProjectHours.Add(newProjectHour);
db.SaveChanges();
}
return RedirectToAction("ProjectHourList");
}
}
And on the form:
#model TimesheetMVC.Models.ProjectHour
...
#Html.DropDownListFor(model => model.employeeId, (SelectList)ViewBag.EmployeeId)
Which is apparently horribly wrong. Any help would be much appreciated...!
Don't use the same name EmployeeId. You need 2 things to create a dropdown list in ASP.NET MVC: a scalar property that will hold the selected value and a collection property that will contain the possible values. But since you are using the ViewBag (which I totally recommend against) you could do the following:
ViewBag.Employees = emp;
and in your view:
#Html.DropDownListFor(
model => model.employeeId,
(IEnumerable<SelectListItem>)ViewBag.Employees
)
But as I said this is not at all an approach that I recommend. I recommend using view models. So define an IEnumerable<SelectListItem> property on your view model:
public IEnumerable<SelectListItem> Employees { get; set; }
and in your controller populate this view model property and then make your view strongly typed to the view model.
Or you could just do a
in the controller
SelectList selectList = new SelectList(db.Employees, "Id", "LastName");
ViewBag.EmployeeList = selectList;
and in the View
#Html.DropDownBoxFor(model => model.id_Employee, ViewBag.EmployeeList as SelectList)
I find this approach easier.
EmployeeId is an IEnumerable<SelectListItem>, not a SelectList.
Therefore, your cast cannot work.
You need to explicitly create a SelectList.