I building simple project just for self-study and i have a little problem.
Im using Visual Studio and Entity Framework.
I builded a ASP.NET MVC 5 app where are CRUD functionality.
In database is connection between 2 tables like on
screenshot
HTTP POST bellow from CarController
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Save(Car car)
{
if (!ModelState.IsValid)
{
var viewModel = new CarFormViewModel()
{
Cars = car,
CarTypeModels = _context.CarTypeModels.ToList()
};
return View("CarForm", viewModel);
}
if (car.Id == 0)
_context.Cars.Add(car);
else
{
var customerInDb = _context.Cars.Single(c => c.Id == car.Id);
customerInDb.Name = car.Name;
customerInDb.HorsePower = car.HorsePower;
customerInDb.LinkToImage = car.LinkToImage;
customerInDb.CarTypeModelId = car.CarTypeModelId;
}
_context.SaveChanges();
return RedirectToAction("Index", "Car");
}
Im getting an error error
Db.CarTypeModel ->
CREATE TABLE [dbo].[CarTypeModels] (
[Id] TINYINT NOT NULL,
[Name] NVARCHAR (MAX) NULL,
CONSTRAINT [PK_dbo.CarTypeModels] PRIMARY KEY CLUSTERED ([Id] ASC));
db.Car ->
CREATE TABLE [dbo].[Cars] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Name] NVARCHAR (255) NULL,
[HorsePower] INT NOT NULL,
[LinkToImage] NVARCHAR (MAX) NULL,
[CarTypeModelId] TINYINT DEFAULT ((0)) NOT NULL,
CONSTRAINT [PK_dbo.Cars] PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_dbo.Cars_dbo.CarTypeModels_CarTypeModelId] FOREIGN KEY ([CarTypeModelId]) REFERENCES [dbo].[CarTypeModels] ([Id]) ON DELETE CASCADE); GO CREATE NONCLUSTERED INDEX [IX_CarTypeModelId] ON [dbo].[Cars]([CarTypeModelId] ASC);
And code from CarForm which using CarTypeModelId
<div class="form-group">
#Html.LabelFor(m => m.Cars.CarTypeModelId)
#Html.DropDownListFor(m => m.Cars.CarTypeModelId, new SelectList(Model.CarTypeModels, "ID", "Name"), "Select car type", new { #class = "form-control" })
#Html.ValidationMessageFor(m => m.Cars.CarTypeModelId)
</div>
I have API Connection and its working fine. I think a problem is in CarController but I really dont know where...
//POST /api/cars
[HttpPost]
public IHttpActionResult CreateCar(CarDto carDto)
{
if (!ModelState.IsValid)
{
return BadRequest();
}
var car = Mapper.Map<CarDto, Car>(carDto);
_context.Cars.Add(car);
_context.SaveChanges();
carDto.Id = car.Id;
return Created(new Uri(Request.RequestUri + "/" + car.Id), carDto);
}
I think your dropdown list selection doesnt work properly and returns car.CarTypeModelId= 0. Try to fix the dropdown list by replacing "ID" by "Id" :
#Html.DropDownListFor(m => m.Cars.CarTypeModelId, new SelectList(Model.CarTypeModels, "Id", "Name"), "Select car type", new { #class = "form-control" })
Related
I'm using MVC 5 with EF6 and Database first..
I have two tables, table A and B, both of them with non nullable fields.
I did the same procedure for both of them, create the controller and the view, but for some reason, the html of the view to create records for table B does not generate the client validations.
Table A:
CREATE TABLE [dbo].[A](
[ID] [int] IDENTITY(1,1) NOT NULL,
[CodA] [int] NOT NULL,
[Volume] [decimal](15, 2) NOT NULL,
[CreationDate] [datetime] NOT NULL,
CONSTRAINT [A_pk] PRIMARY KEY CLUSTERED
(
[ID] ASC
)
Table B:
CREATE TABLE [dbo].[B](
[ID] [smallint] IDENTITY(1,1) NOT NULL,
[Codigo] [varchar](3) NOT NULL,
[Iso2] [varchar](2) NOT NULL,
[Iso3] [varchar](3) NOT NULL,
[Designation] [nvarchar](128) NOT NULL,
CONSTRAINT [B_pk] PRIMARY KEY CLUSTERED
(
[ID] ASC
)
Html for a field in a view to create a record in table A:
<input class="form-control text-box single-line" data-val="true" data-val-number="The field Volume must be a number." data-val-required="The Volume field is required." id="Volume" name="Volume" type="text" value="">
Code from the cshtml create file for table A:
#Html.EditorFor(model => model.Volume, new { htmlAttributes = new { #class = "form-control" } })
Html for a field in a view to create a record in table B:
<input class="form-control text-box single-line" id="Codigo" name="Codigo" type="text" value="">
Code from the cshtml create file for table B:
#Html.EditorFor(model => model.Iso3, new { htmlAttributes = new { #class = "form-control" } })
Controller for the create action for table A
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(A a)
{
if(ModelState.IsValid)
{
db.A.Add(a);
db.SaveChanges();
return RedirectToAction("Index", "Backoffice");
}
return View(a);
}
Controller for the create action for table B
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Create(B b)
{
if (ModelState.IsValid)
{
db.B.Add(b);
db.SaveChanges();
return RedirectToAction("Index", "Backoffice");
}
return View(b);
}
The controllers are identical.
In table A the view shows the validation message for the not nullable fields while in table B it gets to the controller and throws an exception in the SaveChanges method.
I think you need to add data validation attribute
[Required(AllowEmptyStrings = false)] to your class properties.
I have 2 tables, Users and Employees
CREATE TABLE [dbo].[Users](
[UserID] [int] IDENTITY NOT NULL,
[Username] [nvarchar](8) NOT NULL,
[Activo] [bit] NOT NULL,
[UltimoAcesso] [datetime] NULL,
PRIMARY KEY (UserID)
)
CREATE TABLE [dbo].[Employees](
[ColaboradorID] [int] IDENTITY(1,1) NOT NULL,
[Nome] [nvarchar](100) NOT NULL,
[Email] [nvarchar](100) NULL,
[UserID] [int] NULL
PRIMARY KEY(ColaboradorID),
UNIQUE (UserID)
)
ALTER TABLE [dbo].[Employees] WITH CHECK ADD CONSTRAINT [FK_Employees_UtilizadorID] FOREIGN KEY([UserID])
REFERENCES [dbo].[Users] ([UserID])
ON UPDATE CASCADE
ON DELETE CASCADE
I'm using Entity FrameWork Database first.
I'm trying to insert a new user
public void fvAddUser_InsertItem()
{
var item = new InventarioCiclico.Users();
using (InventarioCiclicoContext db = new InventarioCiclicoContext())
{
Employee c = new Employee ();
c.Nome = (fvAddUser.FindControl("txtNome") as TextBox).Text;
c.Email = (fvAddUser.FindControl("txtEmail") as TextBox).Text;
item.Employee.Add(c);
var employee = db.Set<Employee>();
TryUpdateModel(item);
if (ModelState.IsValid)
{
if (db.Users.Any(u => u.Username == item.Username))
{
// Handle exception
}
else
{
db.Users.Add(item);
db.SaveChanges();
var userID = item.UserID;
c.UserID = userID;
employee.Add(c);
db.SaveChanges();
}
}
}
}
However it keeps giving me exception of violation of unique value? Before starting with entity framework I would insert on Users table first, get scope_identity and insert on Employee table after and I'm trying to do this using EF6 but i don't know what can i do about this.
You are adding two employees with the same UserId in the database and since UserId is a unique field in employee table you are getting the exception of violation of unique value.
In the line item.Employee.Add(c); you are add the employee to the user, therefore, when adding the user to the database, the employee will be added two. So you don't need the last three lines:
c.UserID = userID;
employee.Add(c);
db.SaveChanges();
I have ASP.NET MVC app
I have two relative tables Companies and Vacancies.
When I delete Company, I want to delete relative to it Vacancies.
Here is my controller
public ActionResult Delete(int? id)
{
if (id == null)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
Company companies = db.Companies.Find(id);
if (companies == null)
{
return HttpNotFound();
}
return View(companies);
}
// POST: Companies/Delete/5
[HttpPost, ActionName("Delete")]
[ValidateAntiForgeryToken]
public ActionResult DeleteConfirmed(int id)
{
Company companies = db.Companies.Find(id);
db.Companies.Remove(companies);
db.SaveChanges();
return RedirectToAction("Index");
}
And here is Companies table
CREATE TABLE [dbo].[Companies] (
[CompanyID] INT IDENTITY (1, 1) NOT NULL,
[CompanyName] NVARCHAR (MAX) NULL,
PRIMARY KEY CLUSTERED ([CompanyID] ASC)
);
AnŠ² vacancies
CREATE TABLE [dbo].[Vacancies] (
[VacancyId] INT IDENTITY (1, 1) NOT NULL,
[VacancyName] NCHAR (10) NULL,
[CompanyID] INT NULL,
PRIMARY KEY CLUSTERED ([VacancyId] ASC),
CONSTRAINT [FK_Vacancies_ToTable] FOREIGN KEY ([CompanyID]) REFERENCES [dbo].[Companies] ([CompanyID])
);
How I need to modify my syntax to easily delete company?
Modify your dependent to add ON DELETE CASCADE
CREATE TABLE [dbo].[Vacancies] (
[VacancyId] INT IDENTITY (1, 1) NOT NULL,
[VacancyName] NCHAR (10) NULL,
[CompanyID] INT NULL,
PRIMARY KEY CLUSTERED ([VacancyId] ASC),
CONSTRAINT [FK_Vacancies_ToTable]
FOREIGN KEY ([CompanyID])
REFERENCES [dbo].[Companies] ([CompanyID])
ON DELETE CASCADE);
This will allow delete your references when you delete you're company.
Alternatively you can mark each entity as deleted from C#, this will give you more control and avoid accidental deletes
I have simple database. Let i add using AddBookName record in table NamesSet database should generate random BookNameID. The main question is how to figure out the BookNameID that was generated to establish a connection to table Books?
Books:
CREATE TABLE [dbo].[BooksSet] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[BookNameID] NVARCHAR (MAX) NOT NULL,
[PlaceID] NVARCHAR (MAX) NOT NULL,
CONSTRAINT [PK_BooksSet] PRIMARY KEY CLUSTERED ([Id] ASC)
);
Names
CREATE TABLE [dbo].[NamesSet] (
[BookNameID] INT IDENTITY (1, 1) NOT NULL,
[BookName] NVARCHAR (MAX) NOT NULL,
[Language] NVARCHAR (MAX) NOT NULL,
CONSTRAINT [PK_NamesSet] PRIMARY KEY CLUSTERED ([BookNameID] ASC)
);
HomeController:
public class HomeController : Controller
{
//
// GET: /Home/
TestEntities TE = new TestEntities();
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult AddBookName(Names name)
{
TE.NamesSet.Add(name);
TE.SaveChanges();
return View();
}
}
View:
#model TestDataBase.Models.Names
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
#using(#Html.BeginForm("AddBookName","Home"))
{
#Html.EditorFor(x=>x.BookName)
#Html.EditorFor(x => x.Language)
<input type="submit" value="Add name"/>
}
When you call SaveChanges(), any objects added to the context will be populated with the generated values from the database. So the generated value should be available after that line, in:
name.BookNameID
I am getting the exception while adding object in database (Sqlite I am currently using).
Exception: The member with identity '' does not exist in the metadata collection. Parameter name: identity
Normally this code works on my local but I want to run this project my netbook too but whatever I do I cant find the way which make it run.
Any help will be greately appreciated.
-- Original table schema
CREATE TABLE [Content] (
[Id] integer PRIMARY KEY AUTOINCREMENT NOT NULL,
[Title] text NOT NULL,
[Content] text NOT NULL,
[PageId] integer NOT NULL,
[CreatedAt] datetime,
[UpdatedAt] datetime,
[CreatedBy] text,
[UpdatedBy] text,
CONSTRAINT [FK_Content_PageId_Page_Id] FOREIGN KEY ([PageId]) REFERENCES [Page] ([Id])
);
-- Original table schema
CREATE TABLE [Page] (
[Id] integer PRIMARY KEY AUTOINCREMENT NOT NULL,
[Title] text NOT NULL,
[Url] text NOT NULL,
[Visibility] bit NOT NULL,
[CreatedAt] datetime,
[UpdatedAt] datetime,
[CreatedBy] text,
[UpdatedBy] text
);
using (var entities = new PageEntities())
{
var page = entities.Pages.FirstOrDefault(p => p.Id == id);
if (page != null)
{
var content = new Content
{
Title = model.Title,
Explanation = model.Explanation,
CreatedAt = DateTime.Now,
UpdatedAt = DateTime.Now,
PageId = page.Id
};
entities.AddToContents(content);
entities.SaveChanges();
return RedirectToAction("PageContent/" + id, "Admin");
}