Prevent Insert Or Update data in C# or SQL - c#

I have two table Header and Item, that has one to many Relation.
Header Table
Id StartDate EndDate
---------------------------------------
1 1999/1/1 1999/5/1
2 2000/1/1 2000/4/1
3 2000/1/1 2000/5/1
and Item Table
Id HeaderRef SLRef
-------------------------------------
101 1 201
102 2 201
How to Prevent to add Item with HeaderRef=3 and SLRef=201 because it has same SLRef, and the Header rows that HeaderRef referd to it has StartDate and EndDate that another Item with same SLRef Refered to Header in that Range.

Presuming you are using MS SQL Server there are two approaches to achive what you are looking for:
1) Use trigger as suggested by other users. Trigger would be for INSERT / UPDATE that will check the date ranges and will allow new values to be added or raise error.
2) You can use composite primary key in ItemTable:
CREATE TABLE [dbo].[ItemTable](
[Id] [int] IDENTITY(1,1) NOT NULL,
[HeaderRef] [int] NOT NULL,
[SLRef] [int] NOT NULL,
PRIMARY KEY CLUSTERED
(
[HeaderRef] ASC,
[SLRef] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
Now this will put a constraint on the ItemTable and sql server WILL NOT allow duplicate combination of headerRef and SLRef int values (keys).
Back you your HeaderTable, you can put the unique constraint to stop duplicating the range of start and end dates
CREATE TABLE [dbo].[HeaderTable](
[ID] [int] IDENTITY(1,1) NOT NULL,
[STARTDATE] [datetime] not NULL,
[ENDDATE] [datetime] not NULL,
CONSTRAINT [PK_HeaderTable] PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
Now create unique index on HeaderTable for start and end dates.
/****** Object: Index [IX_HeaderTable] Script Date: 03/13/2017 12:24:51 ******/
CREATE UNIQUE NONCLUSTERED INDEX [IX_HeaderTable] ON [dbo].[HeaderTable]
(
[ENDDATE] ASC,
[STARTDATE] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
GO
You can also put another constraint on HeaderTable that will check if start date cant be before end date.
ALTER TABLE [dbo].[HeaderTable] WITH CHECK ADD CONSTRAINT [CheckEndLaterThanStart] CHECK (([ENDDATE]>=[STARTDATE]))
GO
ALTER TABLE [dbo].[HeaderTable] CHECK CONSTRAINT [CheckEndLaterThanStart]
GO
Hope this helps!

You Are Looking For a DML Trigger , in simple terms it's some sort of a sql function or procedure that is called automatically when the user try to change the data inside a database by adding or removing , Also the body of the trigger can contain some validation logic so it won't insert the data unless it meets a certain condition

Related

Is there a way I can better structure this LINQ query?

I'm working on a new WPF application. It needs to display the results of a query in a datagrid when it launches. In testing I've found that under certain circumstances the time it takes for the query to run can be 2 minutes - unacceptably long. However, under other circumstances it can be much faster. The difference depends in part upon where the application is running and I suspect other factors contribute to how fast it can run. Being closer to the server (on-prem) then it is only a matter of a few seconds, although it will run faster at other offices even further away from the server. Most of us are still working from home. At my home I have incredibly good Internet speeds (for my state), but I still have abysmal performance on that query.
But I've no idea at this point how fast that query will run for the users, who are as far away from the server as I am. Here's the LINQ query to retrieve the data. Can I restructure the LINQ better for better performance?
using (var ctx = new AppEntities())
{
People = ctx.People.AsNoTracking().Where(p => p.Inactive == false)
.Include(p => p.Agency)
.Include(p => p.PersonnelCertifications.Select(pc => pc.CertificationType))
.Where(p => p.PersonnelCertifications.Any(pc => pc.CertificationType.CertType == "Operator"))
.OrderBy(p => p.LastName)
.ThenBy(p => p.FirstName)
.ToList();
}
Here's the primary table Person:
CREATE TABLE [app].[Person](
[ID] [bigint] IDENTITY(1,1) NOT NULL,
[AgencyID] [bigint] NOT NULL,
[LastName] [nvarchar](25) NOT NULL,
[FirstName] [nvarchar](20) NOT NULL,
--other columns removed for brevity
CONSTRAINT [PK_Person] 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 = 100) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
And table Agency:
CREATE TABLE [app].[Agency](
[ID] [bigint] IDENTITY(1,1) NOT NULL,
[AgencyCode] [nvarchar](5) NOT NULL,
[AgencyName] [nvarchar](50) NULL,
--other columns removed for brevity
CONSTRAINT [PK_Agency] 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 = 100) ON [PRIMARY],
CONSTRAINT [AK_AgencyCode] UNIQUE NONCLUSTERED
(
[AgencyCode] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 100) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
And table PersonnelCertification:
CREATE TABLE [app].[PersonnelCertification](
[ID] [bigint] IDENTITY(1,1) NOT NULL,
[CertificationTypeID] [bigint] NOT NULL,
[PersonID] [bigint] NOT NULL,
[AgencyID] [bigint] NOT NULL,
--other columns removed for brevity
CONSTRAINT [PK_PersonnelCertification] 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 = 100) ON [PRIMARY]
) ON [PRIMARY]
GO
And finally table CertificationType:
CREATE TABLE [app].[CertificationType](
[ID] [bigint] IDENTITY(1,1) NOT NULL,
[CertType] [nvarchar](30) NOT NULL,
--other columns removed for brevity
CONSTRAINT [PK_CertificationType] 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 = 100) ON [PRIMARY],
CONSTRAINT [CertType] UNIQUE NONCLUSTERED
(
[CertType] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 100) ON [PRIMARY]
) ON [PRIMARY]
GO

How Can I Do Create Table by using sql query in NHibernate?

I have a dynamic table in my project, I doing mapping static table by using Nhibernate fluent API in the model solution. Dynamic table going to create at runtime. dynamic tables have dynamic columns. How can I do Create a dynamic table in NHibernate? thanks for help
CREATE TABLE [dbo].[Events](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](max) NULL,
[StartDate] [datetime] NOT NULL,
[EndDate] [datetime] NOT NULL,
[Quota] [int] NOT NULL,
[Description] [nvarchar](max) NULL,
CONSTRAINT [PK_dbo.Events] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
thanks for help.
I was already using Isession.CreateSqlQuery(sql) but not was working Create table
improved when replace code ' Isession.createSqlQuery(sql).executeUpdate()'

The result of the expression is always true

I made a left join in linq and the value of UserId is NULLABLE (not in the table) but in the join and visual studio shows this warning.
I think this is a false positive because the code works well when userid is null IsSelected is false.
UserPrivilege class
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated from a template.
//
// Manual changes to this file may cause unexpected behavior in your application.
// Manual changes to this file will be overwritten if the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
using System;
using System.Collections.Generic;
public partial class UserPrivileges
{
public int Id { get; set; }
public int UserId { get; set; }
public int PrivilegeId { get; set; }
public virtual Privileges Privileges { get; set; }
public virtual UserProfile UserProfile { get; set; }
}
The linq query:
using (var dataContext = new MyEntities())
{
List<UserPrivilegesModel> result = (from privileges in dataContext.Privileges
join userPrivileges in dataContext.UserPrivileges on privileges.Id equals userPrivileges.PrivilegeId into tmpUserPrivileges
from userPrivileges in tmpUserPrivileges.DefaultIfEmpty()
//where userPrivileges.UserId == userId
select new UserPrivilegesModel { IsSelected = (userPrivileges.UserId != null), Description = privileges.Description, PrivilegeId = privileges.Id }).ToList();
return result;
}
On Linq userid == null is TRUE
SQL SCRIPT:
GO
/****** Object: Table [dbo].[Privileges] Script Date: 07/12/2016 10:35:21 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Privileges](
[Id] [int] IDENTITY(1,1) NOT NULL,
[Name] [nvarchar](20) NOT NULL,
[Description] [nvarchar](100) NOT NULL,
CONSTRAINT [PK_Privileges] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[UserPrivileges] Script Date: 07/12/2016 10:35:21 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[UserPrivileges](
[Id] [int] IDENTITY(1,1) NOT NULL,
[UserId] [int] NOT NULL,
[PrivilegeId] [int] NOT NULL,
CONSTRAINT [PK_UserPrivileges_1] PRIMARY KEY CLUSTERED
(
[UserId] ASC,
[PrivilegeId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[UserProfile] Script Date: 07/12/2016 10:35:21 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[UserProfile](
[UserId] [int] IDENTITY(1,1) NOT NULL,
[UserName] [nvarchar](56) NOT NULL,
[Enabled] [smallint] NULL,
CONSTRAINT [PK__UserProf__1788CC4CB96C92F3] PRIMARY KEY CLUSTERED
(
[UserId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
CONSTRAINT [UQ__UserProf__C9F28456208EB813] UNIQUE NONCLUSTERED
(
[UserName] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[UserPrivileges] WITH CHECK ADD CONSTRAINT [FK_UserPrivileges_Privileges] FOREIGN KEY([PrivilegeId])
REFERENCES [dbo].[Privileges] ([Id])
GO
ALTER TABLE [dbo].[UserPrivileges] CHECK CONSTRAINT [FK_UserPrivileges_Privileges]
GO
ALTER TABLE [dbo].[UserPrivileges] WITH CHECK ADD CONSTRAINT [FK_UserPrivileges_UserProfile] FOREIGN KEY([UserId])
REFERENCES [dbo].[UserProfile] ([UserId])
GO
ALTER TABLE [dbo].[UserPrivileges] CHECK CONSTRAINT [FK_UserPrivileges_UserProfile]
GO
SQL RELATIONSHIP
Should you be checking userPrivlages == null not userPrivlages.UserId == null? Also, should the 2nd from and the join be using the same name?
Try correcting those issues.
The type in the database may be nullable, but the type in the code is not. UserId is of type int, which can never be null. (Hence the error.) So presumably on a class somewhere you have something like this:
public int UserId { get; set; }
To make the type nullable, you would want this:
public int? UserId { get; set; }
Or, if you prefer, this:
public Nullable<int> UserId { get; set; }
This could have implications in other code not shown here about how to use that property, since you're changing the property's type. But this will allow that property to carry a null value.
userPrivaleges.UserId is not nullable, therefore (userPrivalegs.UserId != null) will always be true.

Saving server date and time

I want to save the time and date within my news but in the method below I save the time of the user and if his/her time is wrong, the wrong time will be save. How can I use the server's time instead.
SqlConnection sqlconn = new SqlConnection(connStr);
SqlCommand sqlcmd = new SqlCommand("insert into SubmitManuscript(username,title,authors,type,date,upload,reviewer1,email1,reviewer2,email2,reviewer3,email3)values(#username,#title,#authors,#type,#date,#upload,#reviewer1,#email1,#reviewer2,#email2,#reviewer3,#email3)", sqlconn);
sqlcmd.Parameters.AddWithValue("#username", username);
sqlcmd.Parameters.AddWithValue("#title", Text_Title.Text);
sqlcmd.Parameters.AddWithValue("#authors", Text_Author.Text);
sqlcmd.Parameters.AddWithValue("#type", dd_Type.SelectedItem.Text);
sqlcmd.Parameters.AddWithValue("#date", DateTime.Now);
//sqlcmd.Parameters.AddWithValue("#upload", "~/Suppelment/" +
There is no need to pass datetime parameter. Just set a datetime as default value in your table in the Database. That should do the trick.
Here is a link how to set this in table generation script:
How to set the default value for a datetime column
Edit: Your table needs to have a special DateTimeStamp column that will set system-datetime automatically when you insert a record. I am putting a simple script that you may use as an example.
Note: If you already have table in place then just start from script ALTER TABLE
CREATE TABLE [dbo].[Employee]
(
[EmployeeId] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NULL,
[BirthDate] [datetime] NOT NULL,
[LastUpdateTime] [datetime] NOT NULL,
CONSTRAINT [PK_Employee]
PRIMARY KEY CLUSTERED ([EmployeeId] ASC)
WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF,
IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON,
ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[Employee]
ADD CONSTRAINT [DF_Employee_LastUpdateTime]
DEFAULT (getdate()) FOR [LastUpdateTime]
GO
--- You may also use multiple record insert statement in SQL Server 2008
--- however, I will use a traditional approach here
INSERT INTO [dbo].[Employee] (Name, BirthDate)
VALUES ('Smith', '04/14/1979')
INSERT INTO [dbo].[Employee] (Name, BirthDate)
VALUES ('Jhone', '11/08/1983')
GO

SQL SELECT From two tables (friendship) statement

I have the following tables created:
Table #1: tbl_Connections
USE [taaraf_db]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tbl_Connections](
[uc_Id] [int] IDENTITY(1,1) NOT NULL,
[uc_User] [nvarchar](50) NOT NULL,
[uc_Connection] [nvarchar](50) NOT NULL,
[uc_IsPending] [int] NOT NULL,
[uc_DateTime] [datetime] NOT NULL,
CONSTRAINT [PK_tbl_Connections] PRIMARY KEY CLUSTERED
(
[uc_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[tbl_Connections] ADD CONSTRAINT [DF_tbl_Connections_uc_IsPending] DEFAULT ((1)) FOR [uc_IsPending]
GO
Table #2: tbl_LiveStream
USE [taaraf_db]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tbl_LiveStreams](
[ls_Id] [int] IDENTITY(1,1) NOT NULL,
[ls_Story] [nvarchar](max) NOT NULL,
[ls_User] [nvarchar](50) NOT NULL,
[ls_Connection] [nvarchar](50) NOT NULL,
[ls_DateTime] [datetime] NOT NULL,
CONSTRAINT [PK_tbl_LiveStreams] PRIMARY KEY CLUSTERED
(
[ls_Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
GO
Now uc_User in tbl_Connections represents the user who initiated a friend request, and uc_Connection
represents the other party.
Same concept is applied on the second table (tbl_LiveStreams)
I am trying to select all new LiveStreams for a cetrain user, LiveStream should be retrieved for a specific user only if that user is connected to the other party (uc_IsPending = 0)
I have a C# function that takes the following arguments:
public static DataTable GetAsyncLiveStream(string CurrentUser, int startAt, int howMany) { ... }
And with the above, a DataTable should return all new items in LiveStream for the given CurrentUser (ls_User) if the requirements specified above are true.
This is sort of like the Facebook news feed, what's happening with friends etc...
Oh yeah, tbl_LiveStream is populated whenever someone (ls_User) initates some sort of specific event to (ls_Connection).
I'm not sure if i'm complicating my life here but that's what I have and all help is appreciated.
I should mention that I've done this by looping through all returned records from tbl_LiveStream and done some validation using a custom class function .IsFriends() that will go and check for friendship status in the database and programatically populates a DataTable... Which is sort of stupid, I admit. But I'm not sure how to do this.
One last thing,
I'm using the following query to return limited results:
SELECT * FROM (
SELECT row_number() OVER (ORDER BY ) AS rownum, ls_Id
FROM )
AS A
WHERE A.rownum BETWEEN (#start) AND (#start + #rowsperpage)
Please help and thank you for your time.
EDIT
I'd like to note that this is how I am fetching who's friends with who from the tbl_Connections Table.
const string sql = "SELECT REPLACE((uc_Connection + uc_User), #CurrentUser, '') AS Connection " +
"FROM tbl_Connections Connection " +
"WHERE (#CurrentUser = uc_Connection) OR (#CurrentUser = uc_User)";
SELECT * FROM (
SELECT row_number() OVER (ORDER BY ) AS rownum, ls_Id
FROM )
AS A
WHERE A.rownum BETWEEN (#start) AND (#start + #rowsperpage)
This syntax is wrong. You can't do it like that. Use a Union, or use LINQ to SQL.
From a critique perspective, don't get DataTables, get Entities. You seem to be over complicating quite a bit here, with technologies you may not be familiar with. I'd advise taking all currently existing data and dumping it to a CSV file, then starting the application from scratch with something like Sharp Architecture, which can abstract away some of these details for you.

Categories