DELETE statement conflicted (ASP.NET MVC) - c#

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

Related

How to get Identity insert to work with my model

I am trying to allow users to create objects "Rooms". They will be able to add items to the room, and delete and create rooms for their account.
I have my table set up like this,
CREATE TABLE [dbo].[Rooms](
[Value] [money] NULL,
[Name] [nvarchar](50) NOT NULL,
[RoomID] [int] PRIMARY KEY IDENTITY(1,1) NOT NULL,
[User] [nvarchar](128) NOT NULL)
And my insert code like this,
[HttpPost]
public async Task<ActionResult> Create([Bind(Include = "Name, User,
RoomID")] Room room)
{
if (ModelState.IsValid)
{
using (var transaction = db.Database.BeginTransaction())
{
db.Database.ExecuteSqlCommand("SET IDENTITY_INSERT Rooms ON");
room.User = User.Identity.GetUserId();
db.Rooms.Add(room);
await db.SaveChangesAsync();
db.Database.ExecuteSqlCommand("SET IDENTITY_INSERT Rooms OFF");
transaction.Commit();
}
return RedirectToAction("Index");
}
return View(room);
}
Whenever I try adding an object room to my database, I leave the RoomID undefined. I expect the database to automatically increment the ID, but it is throwing an error....
Violation of PRIMARY KEY constraint 'PK__Rooms__328639191EFADF47'. Cannot insert duplicate key in object 'dbo.Rooms'. The duplicate key value is (0).
The statement has been terminated.
It is setting the value of RoomID to 0 everytime.

One to One relation in Entity frame work Insert

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();

Insert Data using entity framemodel

I am a student and working on a college project.
I have created a simple scenario which I am facing in my project.
The simple database looks like this.
**Location Table**
CREATE TABLE [dbo].[Location] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[longitude] VARCHAR (50) NULL,
[latitude] VARCHAR (50) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
**Role Table**
CREATE TABLE [dbo].[Role] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Name] VARCHAR (50) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
**Another table**
CREATE TABLE [dbo].[Another] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[Anything] VARCHAR (50) NULL,
PRIMARY KEY CLUSTERED ([Id] ASC)
);
**User Table**
CREATE TABLE [dbo].[User] (
[Id] INT IDENTITY (1, 1) NOT NULL,
[name] VARCHAR (50) NULL,
[address] VARCHAR (50) NULL,
[loc_id] INT NOT NULL,
[role_id] INT NOT NULL,
[another_id] INT NOT NULL,
PRIMARY KEY CLUSTERED ([Id] ASC),
CONSTRAINT [FK_User_lococation] FOREIGN KEY ([loc_id]) REFERENCES [dbo].[Location] ([Id]),
CONSTRAINT [FK_User_another] FOREIGN KEY ([another_id]) REFERENCES [dbo].[Another] ([Id]),
CONSTRAINT [FK_User_role] FOREIGN KEY ([role_id]) REFERENCES [dbo].[Role] ([Id])
);
I have populated Role table with following values
enter image description here
Now I want to add user using EntityFrameWorkCore
My controller looks like this
[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([Bind("Id,Name,Address,RoleId")] User user)
{
if (ModelState.IsValid)
{
_context.Add(user);
await _context.SaveChangesAsync();
return RedirectToAction(nameof(Index));
}
ViewData["LocId"] = new SelectList(_context.Location, "Id", "Id", user.LocId);
ViewData["RoleId"] = new SelectList(_context.Role, "Id", "Id", user.RoleId);
return View(user);
}
The problem is I want to Add User but it doesn't have a foreign key of Location table and Another table.
How can I create a Location_id and Another_id and put in User
I want my User object to get the foreign key of location table and another table.
Please help me, I don't know how to do that it will great help for me.Thanks
If you don't have info about FK, don't generate it randomly, make foreign key column nullable in class user. Surely, when you are using EF you have navigation properties in User class. You can add also int property which stores id of associated entity (this is advised, so if you don't have, create such property). Type of this property should (obviously) nullable, so use int?. Then update database, so FK column in DB will be also nullable. Then you will be able to insert user entity.

asp.net mvc database relationship

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

Error trying to login into ASP.NET Identity 2, column UserId not valid

After a lot of time working with ASP.NET Membership, at last I've some spare free time to dig into Identity and try to upgrade our developing framework to use it.
So... I'm reading a lot of info, tutorials into the matter and trying to put it to work.
At this moment, I've been able to register users into the database and assign roles to them. I've also changed the model to differenciate between username and email for user accounts, as usually into our applications we don't use email accounts for user identification.
However, I've hit a wall with login. When controller tries to execute PasswordSignInAsync I receive an unhandled exception like this:
System.Data.SqlClient.SqlException: Column name 'UserId' is not valid. Column name 'UserId' is not valid.
I'm totally lost with this problem, I don't see where those UserId columns are coming from (the only ones on database model are on AspNetUserRoles and in AspNetUserLogins) or why they aren't being recognized during query execution.
This is the controller Login action:
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl) {
if (!ModelState.IsValid) {
return View(model);
}
var result = await SignInManager.PasswordSignInAsync(model.username, model.Password, model.RememberMe, shouldLockout: true);
switch (result) {
case SignInStatus.Success:
return RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "Login error.");
return View(model);
}
}
The only change respect the base project is that I've changed the first parameter on the call from model.Email to model.username.
Any insight on the problem, how to trace or fix it will be much appreciated.
The problem could be that your database doesn't match the database model that your code is expecting.
Here's the ASP.NET Identity database as generated by code-first in a brand new ASP.NET MVC project with Identity from VS2013:
CREATE TABLE [dbo].[AspNetRoles] (
[Id] [nvarchar](128) NOT NULL,
[Name] [nvarchar](256) NOT NULL,
CONSTRAINT [PK_dbo.AspNetRoles] PRIMARY KEY ([Id])
)
CREATE UNIQUE INDEX [RoleNameIndex] ON [dbo].[AspNetRoles]([Name])
CREATE TABLE [dbo].[AspNetUserRoles] (
[UserId] [nvarchar](128) NOT NULL,
[RoleId] [nvarchar](128) NOT NULL,
CONSTRAINT [PK_dbo.AspNetUserRoles] PRIMARY KEY ([UserId], [RoleId])
)
CREATE INDEX [IX_UserId] ON [dbo].[AspNetUserRoles]([UserId])
CREATE INDEX [IX_RoleId] ON [dbo].[AspNetUserRoles]([RoleId])
CREATE TABLE [dbo].[AspNetUsers] (
[Id] [nvarchar](128) NOT NULL,
[Email] [nvarchar](256),
[EmailConfirmed] [bit] NOT NULL,
[PasswordHash] [nvarchar](max),
[SecurityStamp] [nvarchar](max),
[PhoneNumber] [nvarchar](max),
[PhoneNumberConfirmed] [bit] NOT NULL,
[TwoFactorEnabled] [bit] NOT NULL,
[LockoutEndDateUtc] [datetime],
[LockoutEnabled] [bit] NOT NULL,
[AccessFailedCount] [int] NOT NULL,
[UserName] [nvarchar](256) NOT NULL,
CONSTRAINT [PK_dbo.AspNetUsers] PRIMARY KEY ([Id])
)
CREATE UNIQUE INDEX [UserNameIndex] ON [dbo].[AspNetUsers]([UserName])
CREATE TABLE [dbo].[AspNetUserClaims] (
[Id] [int] NOT NULL IDENTITY,
[UserId] [nvarchar](128) NOT NULL,
[ClaimType] [nvarchar](max),
[ClaimValue] [nvarchar](max),
CONSTRAINT [PK_dbo.AspNetUserClaims] PRIMARY KEY ([Id])
)
CREATE INDEX [IX_UserId] ON [dbo].[AspNetUserClaims]([UserId])
CREATE TABLE [dbo].[AspNetUserLogins] (
[LoginProvider] [nvarchar](128) NOT NULL,
[ProviderKey] [nvarchar](128) NOT NULL,
[UserId] [nvarchar](128) NOT NULL,
CONSTRAINT [PK_dbo.AspNetUserLogins] PRIMARY KEY ([LoginProvider], [ProviderKey], [UserId])
)
CREATE INDEX [IX_UserId] ON [dbo].[AspNetUserLogins]([UserId])
ALTER TABLE [dbo].[AspNetUserRoles] ADD CONSTRAINT [FK_dbo.AspNetUserRoles_dbo.AspNetRoles_RoleId] FOREIGN KEY ([RoleId]) REFERENCES [dbo].[AspNetRoles] ([Id]) ON DELETE CASCADE
ALTER TABLE [dbo].[AspNetUserRoles] ADD CONSTRAINT [FK_dbo.AspNetUserRoles_dbo.AspNetUsers_UserId] FOREIGN KEY ([UserId]) REFERENCES [dbo].[AspNetUsers] ([Id]) ON DELETE CASCADE
ALTER TABLE [dbo].[AspNetUserClaims] ADD CONSTRAINT [FK_dbo.AspNetUserClaims_dbo.AspNetUsers_UserId] FOREIGN KEY ([UserId]) REFERENCES [dbo].[AspNetUsers] ([Id]) ON DELETE CASCADE
ALTER TABLE [dbo].[AspNetUserLogins] ADD CONSTRAINT [FK_dbo.AspNetUserLogins_dbo.AspNetUsers_UserId] FOREIGN KEY ([UserId]) REFERENCES [dbo].[AspNetUsers] ([Id]) ON DELETE CASCADE
Compare your database to this structure and it should work :)

Categories

Resources