One to One relation in Entity frame work Insert - c#

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

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.

Creating WishList/ShopingCart for ASP.net mvc problems with foreign keys

Creating shop application and having two main tables Product and Customer. The aim is to create an Order table where customer can choose from the productgetall list and add it to Order table.
Customer Table
CREATE TABLE [dbo].[Customer]
(
[CustomerId] INT IDENTITY (1, 1) NOT NULL,
[FirstName] NVARCHAR(40) NOT NULL,
[LastName] NVARCHAR(20) NOT NULL,
[Email] NVARCHAR(60) NOT NULL,
[Photo] VARBINARY(MAX) NULL,
[password] VARCHAR(300) NULL,
[Country] VARCHAR(50) NULL,
CONSTRAINT [PK_Customer]
PRIMARY KEY CLUSTERED ([CustomerId] ASC)
);
Product table:
CREATE TABLE [dbo].[Product]
(
[ProductId] INT IDENTITY (1, 1) NOT NULL,
[ProductName] NVARCHAR(50) NOT NULL,
[ProductDetails] TEXT NULL,
[ProductPrice] INT NOT NULL,
[ProductCategory] NVARCHAR(50) NULL,
PRIMARY KEY CLUSTERED ([ProductId] ASC)
);
Order table
CREATE TABLE [dbo].[Order]
(
[OrderId] INT IDENTITY (1, 1) NOT NULL,
[CustomerId] INT NOT NULL,
[ProductId] INT NOT NULL,
[Date] DATE NULL,
[Time] TIME(7) NULL,
CONSTRAINT [ORDER_PK]
PRIMARY KEY CLUSTERED ([OrderId] ASC),
CONSTRAINT [CUSTOMER_FK]
FOREIGN KEY ([CustomerId])
REFERENCES [dbo].[Customer] ([CustomerId])
ON DELETE CASCADE ON UPDATE CASCADE,
CONSTRAINT [PRODUCT_FK]
FOREIGN KEY ([ProductId])
REFERENCES [dbo].[Product] ([ProductId])
ON DELETE CASCADE ON UPDATE CASCADE
);
C# code to add order
public void AddOrder(Order a)
{
using (DbConnection conn = new SqlConnection(ConnStr))
{
using (DbCommand cmd = conn.CreateCommand())
{
cmd.CommandTimeout = 120;
cmd.CommandText = #"INSERT INTO [dbo].[Order] (CustomerId, ProductId, Date, Time)
VALUES (#CustomerId, #ProductId, #Date, #Time)";
cmd.AddParameter("#CustomerId", a.CustomerId, DbType.Int32);
cmd.AddParameter("#ProductId", a.ProductId, DbType.Int32);
cmd.AddParameter("#Date", a.Date, DbType.Date);
cmd.AddParameter("#Time", a.Time.ToString(), DbType.String);
conn.Open();
cmd.ExecuteScalar();
}
}
}
While creating through web forms it showing error on ExecuteScalar:
System.Data.SqlClient.SqlException: 'The INSERT statement conflicted with the FOREIGN KEY constraint "CUSTOMER_FK". The conflict occurred in database "C:\USERS\USER\DESKTOP\2019 5LVL\DBSD\TRYWISHLIST\3\00005466\00005466\APP_DATA\KFCDB.MDF", table "dbo.Customer", column 'CustomerId'. The statement has been terminated
The CustomerId you're sending does not exist in dbo.Customer, insert it.

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.

EF 6: inserting multiple - The relationship could not be changed because one or more of the foreign-key properties is non-nullable

I've run across this a few times in our system in the past, but haven't found the reasoning...
In essence I have a Contact, and the contact has a nullable PhoneNumber.
The code Loops through a list of View Models, maps them to the Data Models, then (after all models are mapped) calls SaveChanges().
The test data has the data for the phone number duplicated. When I alter the test data to have different phone numbers for each contact, everything saves fine.
Here's a stripped down simple sample of what I'm doing that exhibits the behavior.
class Program
{
static void Main(string[] args)
{
TestWeirdEDMXIssue();
Console.ReadLine();
}
static void TestWeirdEDMXIssue()
{
List<dynamic> works = new List<dynamic>
{
new { FirstName = "Fred", LastName = "Snider", PhoneNumber = "888-888-8881", CountryID = 1 },
new { FirstName = "Ted", LastName = "Snider", PhoneNumber = "888-888-8882", CountryID = 1 },
new { FirstName = "Mike", LastName = "Snider", PhoneNumber = "888-888-8883", CountryID = 1 },
new { FirstName = "Tim", LastName = "Snider", PhoneNumber = "888-888-8884", CountryID = 1 },
new { FirstName = "Todd", LastName = "Snider", PhoneNumber = "888-888-8885", CountryID = 1 },
new { FirstName = "Terry", LastName = "Snider", PhoneNumber = "888-888-8886", CountryID = 1 }
};
List<dynamic> broken = new List<dynamic>
{
new { FirstName = "Fred", LastName = "Snider", PhoneNumber = "888-888-8888", CountryID = 1 },
new { FirstName = "Ted", LastName = "Snider", PhoneNumber = "888-888-8888", CountryID = 1 },
new { FirstName = "Mike", LastName = "Snider", PhoneNumber = "888-888-8888", CountryID = 1 },
new { FirstName = "Tim", LastName = "Snider", PhoneNumber = "888-888-8888", CountryID = 1 },
new { FirstName = "Todd", LastName = "Snider", PhoneNumber = "888-888-8888", CountryID = 1 },
new { FirstName = "Terry", LastName = "Snider", PhoneNumber = "888-888-8888", CountryID = 1 }
};
TestWeirdEDMXIssueSave(works); //Completes with "Success!"
TestWeirdEDMXIssueSave(broken); //Throws Exception
}
static void TestWeirdEDMXIssueSave(List<dynamic> data)
{
try
{
using (var context = new DBEntities())
{
var creatorID = context.UserProfiles.FirstOrDefault(up => up.Contact.FirstName == "automationtestuser")?.ID ?? Guid.Empty;
foreach (var item in data)
{
var contact = context.Contacts.Create();
context.Contacts.Add(contact);
contact.ID = Guid.NewGuid();
contact.FirstName = item.FirstName;
contact.LastName = item.LastName;
contact.CreationDate = DateTime.Now;
contact.CreatedBy = creatorID;
var phoneNumber = context.PhoneNumbers.Create();
context.PhoneNumbers.Add(phoneNumber);
//PhoneNumber ID is Identity
phoneNumber.CreatedBy = creatorID;
phoneNumber.CreationDate = DateTime.Now;
phoneNumber.TypeID = (int)PhoneNumberTypes.Office;
phoneNumber.Number = item.PhoneNumber;
phoneNumber.CountryID = item.CountryID;
contact.PhoneNumber = phoneNumber;
}
context.SaveChanges();
}
Console.WriteLine("Success!");
}
catch (Exception ex)
{
Console.WriteLine(ex);
}
}
}
OUTPUT
Success!
System.InvalidOperationException: The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.
at System.Data.Entity.Core.Objects.ObjectContext.PrepareToSaveChanges(SaveOptions options)
at System.Data.Entity.Core.Objects.ObjectContext.SaveChangesInternal(SaveOptions options, Boolean executeInExistingTransaction)
at System.Data.Entity.Core.Objects.ObjectContext.SaveChanges(SaveOptions options)
at System.Data.Entity.Internal.InternalContext.SaveChanges()
at System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
at System.Data.Entity.DbContext.SaveChanges()
...(My Code)...
EDIT
Here are the create scripts for the Tables (sql generated, so its a bit ugly):
Contact
CREATE TABLE [Common].[Contacts](
[ID] [uniqueidentifier] NOT NULL,
[FirstName] [varchar](25) NOT NULL,
[MiddleInitial] [char](1) NULL,
[LastName] [varchar](50) NOT NULL,
[Title] [varchar](50) NULL,
[Description] [varchar](255) NULL,
[ContactEmailAddress] [varchar](100) NULL,
[ContactPhoneNumberID] [int] NULL,
[ContactFaxNumberID] [int] NULL,
[AddressID] [int] NULL,
[ACHDate] [datetime] NULL,
[CreatedBy] [uniqueidentifier] NOT NULL,
[CreationDate] [datetime] NOT NULL,
[IsMarkedAsDeleted] [bit] NOT NULL,
[Position] [varchar](50) NULL,
[MiddleName] [varchar](50) NULL,
[LastThenFirstName] AS (case when [LastName] IS NULL OR len(rtrim([LastName]))=(0) then [FirstName] when [FirstName] IS NULL OR len(rtrim([FirstName]))=(0) then [LastName] else (rtrim(ltrim([LastName]))+', ')+rtrim(ltrim([FirstName])) end) PERSISTED,
[FirstThenLastName] AS (rtrim(ltrim((isnull([FirstName],'')+' ')+isnull([LastName],'')))) PERSISTED,
[AuthenticatorPin] [int] NULL,
[AuthenticatorCode] [int] NULL,
CONSTRAINT [PK_Contacts] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 80) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [Common].[Contacts] ADD CONSTRAINT [DF_Contacts_ID] DEFAULT (newid()) FOR [ID]
GO
ALTER TABLE [Common].[Contacts] ADD CONSTRAINT [DF_Contacts_CreationDate] DEFAULT (getdate()) FOR [CreationDate]
GO
ALTER TABLE [Common].[Contacts] ADD CONSTRAINT [DF_Contacts_IsMarkedAsDeleted] DEFAULT ((0)) FOR [IsMarkedAsDeleted]
GO
ALTER TABLE [Common].[Contacts] WITH CHECK ADD CONSTRAINT [FK_Contacts_AddressID_Addresses_ID] FOREIGN KEY([AddressID])
REFERENCES [Common].[Addresses] ([ID])
GO
ALTER TABLE [Common].[Contacts] CHECK CONSTRAINT [FK_Contacts_AddressID_Addresses_ID]
GO
ALTER TABLE [Common].[Contacts] WITH CHECK ADD CONSTRAINT [FK_Contacts_ContactFaxNumberID_PhoneNumbers_ID] FOREIGN KEY([ContactFaxNumberID])
REFERENCES [Common].[PhoneNumbers] ([ID])
GO
ALTER TABLE [Common].[Contacts] CHECK CONSTRAINT [FK_Contacts_ContactFaxNumberID_PhoneNumbers_ID]
GO
ALTER TABLE [Common].[Contacts] WITH CHECK ADD CONSTRAINT [FK_Contacts_ContactPhoneNumberID_PhoneNumbers_ID] FOREIGN KEY([ContactPhoneNumberID])
REFERENCES [Common].[PhoneNumbers] ([ID])
GO
ALTER TABLE [Common].[Contacts] CHECK CONSTRAINT [FK_Contacts_ContactPhoneNumberID_PhoneNumbers_ID]
GO
ALTER TABLE [Common].[Contacts] WITH CHECK ADD CONSTRAINT [FK_Contacts_CreatedBy_UserProfiles_ID] FOREIGN KEY([CreatedBy])
REFERENCES [Common].[UserProfiles] ([ID])
GO
ALTER TABLE [Common].[Contacts] CHECK CONSTRAINT [FK_Contacts_CreatedBy_UserProfiles_ID]
GO
Phone Numbers
CREATE TABLE [Common].[PhoneNumbers](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Number] [varchar](20) NOT NULL,
[Extension] [varchar](10) NULL,
[TypeID] [int] NOT NULL,
[CountryID] [int] NOT NULL,
[CreatedBy] [uniqueidentifier] NOT NULL,
[CreationDate] [datetime] NOT NULL,
[IsMarkedAsDeleted] [bit] NOT NULL,
CONSTRAINT [PK_PhoneNumbers] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 80) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [Common].[PhoneNumbers] ADD CONSTRAINT [DF_PhoneNumbers_CreationDate] DEFAULT (getdate()) FOR [CreationDate]
GO
ALTER TABLE [Common].[PhoneNumbers] ADD CONSTRAINT [DF_PhoneNumbers_IsMarkedAsDeleted] DEFAULT ((0)) FOR [IsMarkedAsDeleted]
GO
ALTER TABLE [Common].[PhoneNumbers] WITH CHECK ADD CONSTRAINT [FK_PhoneNumbers_CountryID_Countries_ID] FOREIGN KEY([CountryID])
REFERENCES [Common].[Countries] ([ID])
GO
ALTER TABLE [Common].[PhoneNumbers] CHECK CONSTRAINT [FK_PhoneNumbers_CountryID_Countries_ID]
GO
ALTER TABLE [Common].[PhoneNumbers] WITH CHECK ADD CONSTRAINT [FK_PhoneNumbers_CreatedBy_UserProfiles_ID] FOREIGN KEY([CreatedBy])
REFERENCES [Common].[UserProfiles] ([ID])
GO
ALTER TABLE [Common].[PhoneNumbers] CHECK CONSTRAINT [FK_PhoneNumbers_CreatedBy_UserProfiles_ID]
GO
ALTER TABLE [Common].[PhoneNumbers] WITH CHECK ADD CONSTRAINT [FK_PhoneNumbers_TypeID_PhoneNumberTypes_ID] FOREIGN KEY([TypeID])
REFERENCES [Common].[PhoneNumberTypes] ([ID])
GO
ALTER TABLE [Common].[PhoneNumbers] CHECK CONSTRAINT [FK_PhoneNumbers_TypeID_PhoneNumberTypes_ID]
GO
Depending on how your entities are mapped and the relationship between PhoneNumber and Contact, the data may not be persisting as you expect. Ideally you should use database generated IDs for all entities and use navigation properties to manage the related entities.
Based on the examples, check that the schema has a PhoneNumberId column on Contact, and that it is a FK to the PhoneNumber table's PK. Also check that the relationship between contact and phone number is set up correctly. For instance either the entity type configuration or DbContext OnModelCreating you should have something like:
If your Contact entity declares a PhoneNumberId FK field:
HasRequired(x => x.PhoneNumber)
.WithMany()
.HasForeignKey(x => x.PhoneNumberId);
or if the entity does not declare the FK field, but the table has the FK:
HasRequired(x => x.PhoneNumber)
.WithMany()
.Map(x => x.MapKey("PhoneNumberId"));
This forms a many-to-one relationship between contact and phone # which may not be intended since it is possible to use the same phone # record against multiple contacts. (2 contacts may share the same phone #, but changing the phone # on one should not necessarily update the # of the other.) For a 1-to-1 relationship the PhoneNumber table would best be served by using a ContactId as its PK.
IF this relationship is not set up appropriately one way or the other, EF can end up inserting records in the wrong order, not recognizing the required FKs.
In terms of populating your entities, you can be less deliberate with the entity creation and let EF manage the related data:
using (var context = new DBEntities())
{
// A better way to select the ID rather than returning the entire entity:
var creatorID = context.UserProfiles
.Where(up => up.Contact.FirstName == "automationtestuser")
.Select(up => up.ID)
.SingleOrDefault();
foreach (var item in data)
{
var contact = new Contact
{
//contact.ID = Guid.NewGuid(), Definitely recommend letting DB generate ID using NewSequentialId.
FirstName = item.FirstName,
LastName = item.LastName,
CreationDate = DateTime.Now,
CreatedBy = creatorID,
PhoneNumber = new PhoneNumber
{
CreatedBy = creatorID;
CreationDate = DateTime.Now;
TypeID = (int)PhoneNumberTypes.Office;
Number = item.PhoneNumber;
CountryID = item.CountryID;
}
}
context.Contacts.Add(contact);
context.SaveChanges();
}
}
Note that we don't need to create or add phone #'s directly to the DbContext. EF will take care of that using the appropriate relationships and set the FKs for us.
This ensures that the related entities are inserted together and you can avoid adding a DbSet for every entity into your DbContext. (Do you need to search for PhoneNumbers as a top level entity?)
However, to fully determine what is going wrong you should also post any mapping declarations you have, whether code-first annotations, or schema first with entity type configurations or OnModelCreating overrides.

DELETE statement conflicted (ASP.NET MVC)

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

Categories

Resources