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

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

Related

EF Core 2.1 is updating ID when I am simply Loading and Saving

EF Core 2.1 is updating ID when I am simply Loading and Saving values in Database.
Note: I am using Database first approach.
Error : Cannot update identity column 'ID'.
string passportNumber = string.Empty;
using (ApplicationDbContext db = new ApplicationDbContext(connectionString))
{
using (IDbContextTransaction transaction = db.Database.BeginTransaction())
{
try
{
TLifting Lifting = new TLifting();
if (!string.IsNullOrEmpty(PassportNumber))
{
Lifting = db.TLifting.FirstOrDefault();
}
Lifting.Col1 = "TEST"
if (Lifting.PassportId == 0)
{
db.TLifting.Add(Lifting);
}
else
{
db.Entry(Lifting).State = EntityState.Modified;
}
db.SaveChanges();
transaction.Commit();
}
catch (Exception e)
{
}
}
}
Entity
CREATE TABLE [dbo].[T_Lifting](
[ID] [int] IDENTITY(1,1) NOT NULL,
[PassportID] [int] NOT NULL,
[PassportTypeID] AS ((5)) PERSISTED NOT NULL,
CONSTRAINT [PK_T_Lifting_1] PRIMARY KEY CLUSTERED
(
[PassportID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
CONSTRAINT [IX_T_Lifting] UNIQUE NONCLUSTERED
(
[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].[T_Lifting] WITH CHECK ADD CONSTRAINT [FK__T_Lifting__T_Passport] FOREIGN KEY([PassportID], [PassportTypeID])
REFERENCES [dbo].[T_Passport] ([PassportID], [PassportTypeID])
GO
ALTER TABLE [dbo].[T_Lifting] CHECK CONSTRAINT [FK__T_Lifting__T_Passport]
GO
Passport and Piping table are having one one relationship and ID column Identity column.
May be following settings would help you:
In protected override void onModelCreating(ModelBuilder modelBuilder) {} method, write the below line of code accordingly.
modelBuilder.Entity<Type>().Property(u => u.ID).Metadata.SetAfterSaveBehavior(PropertySaveBehavior.Ignore);
Note: Here Type will be class model/object of yours.

Update query giving timeout from C# but working fast from SQL Server

Have an update statement as below:
using (SqlCommand sql_upd = new SqlCommand(#"update table1 set f_name=#file_name,f_date=getdate()
where f_id=#c_no", sql_con))
{
sql_upd.Parameters.AddWithValue("#file_name", "file_n");
sql_upd.Parameters.AddWithValue("#c_no", m_rdr["f_id"].ToString());
sql_upd.ExecuteNonQuery();
}
This is causing a timeout expired error from C#. But the same query is working fine from SQL Server:
Execution Timeout Expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
Table script:
CREATE TABLE [dbo].[table1]
(
[f_id] [varchar](20) NOT NULL,
[f_name] [varchar](75) NULL,
[f_date] [datetime] NULL)
CONSTRAINT [PK_table1]
PRIMARY KEY CLUSTERED ([f_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]

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

Prevent Insert Or Update data in C# or SQL

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

Executing an SQL statement inside c# code gives error "Incorrect syntax near the keyword 'ON'"

The code I have is pretty simple:
SqlCommand command = new SqlCommand("CREATE TABLE [dbo].[ClientData]([ClientDataID] [int] IDENTITY(1,1) NOT NULL,[SessionID] [char](24) NOT NULL,[Browser] [varchar](20) NOT NULL,[IP] [varchar](20) NOT NULL,[OperatingSystem] [varchar](30) NOT NULL,CONSTRAINT [PK_SessionData] PRIMARY KEY CLUSTERED([ClientDataID] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] ON [PRIMARY]");
using (SqlConnection connection = new SqlConnection(connectionString))
{
connection.Open();
command.Connection = connection;
command.ExecuteNonQuery();
}
Upon executing, I get this error:
Incorrect syntax near the keyword 'ON'
The query is generated by MS SQL 2008 and I just copied it as it was. Could someone please tell me why this doesn't work?
Thanks.
You have ON [PRIMARY] twice, but it should only be listed once.
Use this script in SqlCommand.
CREATE TABLE [dbo].[ClientData]([ClientDataID] [int] IDENTITY(1,1) NOT NULL,[SessionID] char NOT NULL,[Browser] varchar NOT NULL,[IP] varchar NOT NULL,[OperatingSystem] varchar NOT NULL,CONSTRAINT [PK_SessionData] PRIMARY KEY CLUSTERED([ClientDataID] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY] )
NOT sure whether you are looking for this!
CREATE TABLE [dbo].[ClientData]
(
[ClientDataID] [int] IDENTITY(1,1)
NOT NULL,[SessionID] [char](24) NOT NULL,
[Browser] [varchar](20) NOT NULL,
[IP] [varchar](20) NOT NULL,
[OperatingSystem] [varchar](30) NOT NULL,
CONSTRAINT [PK_SessionData]
PRIMARY KEY CLUSTERED([ClientDataID] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON)
)

Categories