When the customer logs in with Social Security Number to the website I want it to show the customers Accountname, Accountnumber and Balance. These information have to be fetched through database.
Accounts table:
CREATE TABLE [dbo].[Accounts] (
[id] BIGINT IDENTITY (1, 1) NOT NULL,
[accountnumber] VARCHAR (50) NULL,
[accountname] VARCHAR (50) NULL,
[SSN] BIGINT NOT NULL,
[CustomerId] INT NULL,
[balance] VARCHAR (50) NULL,
[BalanceId] INT NULL,
[AccountId] INT NULL,
CONSTRAINT [PK_dbo.Accounts] PRIMARY KEY CLUSTERED ([id] ASC),
CONSTRAINT [FK_dbo.Accounts_dbo.Customer] FOREIGN KEY ([SSN]) REFERENCES [dbo].[Customer] ([SSN])
);
GO
CREATE NONCLUSTERED INDEX [IX_SSN]
ON [dbo].[Accounts]([SSN] ASC);
Customer table:
CREATE TABLE [dbo].[Customer] (
[id] BIGINT IDENTITY (1, 1) NOT NULL,
[Firstname] VARCHAR (50) NULL,
[Lastname] VARCHAR (50) NULL,
[SSN] BIGINT NOT NULL,
[Password] VARBINARY (MAX) NULL,
[ConfirmPassword] VARCHAR (MAX) NULL,
[Salt] VARCHAR (MAX) NULL,
[AccountId] INT NULL,
[BalanceId] INT NULL,
[RegPayId] INT NULL,
[ConfirmedRegPayId] INT NULL,
[CustomerId] INT NULL,
CONSTRAINT [PK_dbo.Customer] PRIMARY KEY CLUSTERED ([SSN] ASC)
);
But this code shows me no customer:
List<AccountsCTX> everyBalance = db.Accounts.Join(db.Customer, a => a.id,
c => c.SSN,
(a, c) => new AccountsCTX()
{
//id = a.id,
SSN = a.SSN,
accountname = a.accountname,
accountnumber = a.accountnumber,
balance = a.balance
}
).ToList();
return everyBalance;
I have "id" as the primary key from table "Accounts" and "SSN" as the foreign key from table "Customer".
I'm still freshman in programming so need more practice xD
Let me know for more details and appreciate all the help I can get!
actually i dont see any relation between the two tables provided except SSN, this inner join will fetch you all the records which has same SSN id in both the tables:
List<AccountsCTX> everyBalance = db.Accounts.Join(db.Customer, a => a.SSN,
c => c.SSN,
(a, c) => new AccountsCTX()
{
SSN = a.SSN,
accountname = a.accountname,
accountnumber = a.accountnumber,
balance = a.balance
}).Where(x=>x.SSN==InputSSN).ToList();
return everyBalance;
You can try
public static AccountsCTX GetEveryBalance(long currentCustomerSsn)
{
AccountsCTX everyBalance = db.Accounts.Join(db.Customer, a => a.SSN,
c => c.SSN,
(a, c) => new AccountsCTX()
{
//id = a.id,
SSN = a.SSN,
accountname = a.accountname,
accountnumber = a.accountnumber,
balance = a.balance
}
).Where(x=>x.SSN==currentCustomerSsn).FirstOrDefault();//currentCustomerSsn is enter ssn by Customer
return everyBalance;
}
//Create customer
public long insertCusReg(CustomerCTX inCusReg)
{
...
try
{
...
return inCusReg.SSN;
}
catch (Exception)
{
return 0;
}
}
Call Method
currentCustomerSsn=insertCusReg(CustomerCTX);// pass CustomerCTX object
AccountsCTX everyBalance=GetEveryBalance(currentCustomerSsn);
Related
I am trying to pass my DataTable to a stored procedure. The DataTable holds the contents of an Excel sheet. The Excel sheet has two empty columns, five with text, and five with decimal numbers.
The empty columns are OppdragsMVAkode and OppdragsgebyrMVAkode.
If I run my application, I get this exception:
System.ArgumentException: Input string was not in a correct format. Couldn't store <> in OppdragsMVAkode Column. Expected type is Decimal.
If I add a temporary number, I get this exception:
System.Data.SqlClient.SqlException: Error converting data type nvarchar to numeric.
I don't get why it's reading it as a string.
My stored procedure (spGetTrips):
ALTER PROCEDURE [dbo].[spGetTrips]
#trips udtTripsPerMonth readonly
AS
BEGIN
INSERT INTO tblTripsPerMonth
SELECT
[KjøretøyID],
SUBSTRING([År], 7, 4),
SUBSTRING([Måned], 4, 2),
[Betaling (brutto)],
[Betaling (netto)],
[Bestillingsgebyr (netto)],
[Betalingsgebyr (netto)],
[OppdragsMVAkode],
CONCAT(LøyvehaverFakturaID, + 'UF-' + SUBSTRING([År], 9, 2) + SUBSTRING([Måned], 4, 2)),
[Oppdragsgebyr (netto)],
[OppdragsgebyrMVAkode],
CONCAT([RidelRegionFakturaID], + 'UF-' + SUBSTRING([År], 9, 2) + SUBSTRING([Måned], 4, 2))
FROM #trips
UPDATE tblTripsPerMonth
SET [OppdragsMVAkode] = (
SELECT [ID]
FROM [tblMVAkoder]
WHERE [ID] = 'MVAkode2'
);
UPDATE tblTripsPerMonth
SET [OppdragsgebyrMVAkode] = (
SELECT [ID]
FROM [tblMVAkoder]
WHERE [ID] = 'MVAkode5'
);
END
As you can see above, I am setting the value of the two empty columns with UPDATE clauses in the Stored Procedure. Whether they are empty in the Excel sheet, or with some preliminary value, and then to be overridden, I care not - I just want it to work.
Here's my User-Defined Table Type (udtTripsPerMonth):
CREATE TYPE [dbo].[udtTripsPerMonth] AS TABLE(
[KjøretøyID] [nvarchar](50) NULL,
[År] [nvarchar](50) NULL,
[Måned] [nvarchar](50) NULL,
[Betaling (brutto)] [decimal](10, 2) NULL,
[Betaling (netto)] [decimal](10, 2) NULL,
[Bestillingsgebyr (netto)] [decimal](10, 2) NULL,
[Betalingsgebyr (netto)] [decimal](10, 2) NULL,
[OppdragsMVAkode] [decimal](10, 2) NULL,
[LøyvehaverFakturaID] [nvarchar](50) NULL,
[Oppdragsgebyr (netto)] [decimal](10, 2) NULL,
[OppdragsgebyrMVAkode] [decimal](10, 2) NULL,
[RidelRegionFakturaID] [nvarchar](50) NULL
)
GO
And my table (tblTripsPerMonth):
CREATE TABLE [dbo].[tblTripsPerMonth](
[ID] [int] IDENTITY(1,1) NOT NULL,
[KjøretøyID] [nvarchar](50) NULL,
[År] [nvarchar](50) NULL,
[Måned] [nvarchar](50) NULL,
[Betaling (brutto)] [decimal](10, 2) NULL,
[Betaling (netto)] [decimal](10, 2) NULL,
[Bestillingsgebyr (netto)] [decimal](10, 2) NULL,
[Betalingsgebyr (netto)] [decimal](10, 2) NULL,
[OppdragsMVAkode] [decimal](10, 2) NULL,
[LøyvehaverFakturaID] [nvarchar](50) NULL,
[Oppdragsgebyr (netto)] [decimal](10, 2) NULL,
[OppdragsgebyrMVAkode] [decimal](10, 2) NULL,
[RidelRegionFakturaID] [nvarchar](50) NULL,
PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
The other table I reference in the UPDATE clauses (tblMVAkoder):
CREATE TABLE [dbo].[tblMVAkoder](
[ID] [nvarchar](50) NOT NULL,
[Startdato] [date] NULL,
[Sluttdato] [date] NULL,
[MVAsats] [decimal](10, 2) NULL,
PRIMARY KEY CLUSTERED
(
[ID] ASC
)WITH (STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
Here's my C# code (Excel to DataTable):
private void btnExport_Click(object sender, RoutedEventArgs e) {
OpenFileDialog of = new();
of.Filter = "Excel Files | *.xlsx;";
of.Title = "Importer Excel fil.";
if (of.ShowDialog() == true) {
dgPaidTrip.ItemsSource = ImportExceltoDataTable(of.FileName).DefaultView;
btnClearForm.IsEnabled = true;
}
using (SqlConnection con = new(ConnectionString.connectionString))
using (var cmd = new SqlCommand("spGetTrips", con) { CommandType = CommandType.StoredProcedure }) {
con.Open();
DataTable dt = ImportExceltoDataTable(of.FileName);
cmd.Parameters.Add(new SqlParameter("#trips", dt));
cmd.ExecuteNonQuery();
}
}
public static DataTable ImportExceltoDataTable(string filePath) {
using (XLWorkbook wb = new(filePath)) {
IXLWorksheet ws = wb.Worksheet(1);
int tl_Row = ws.FirstCellUsed().Address.RowNumber;
int tl_Col = ws.FirstCellUsed().Address.ColumnNumber;
int br_Row = ws.LastCellUsed().Address.RowNumber;
int br_Col = ws.LastCellUsed().Address.ColumnNumber;
DataTable dt = new();
dt.Columns.Add("KjøretøyID", typeof(string));
dt.Columns.Add("År", typeof(string));
dt.Columns.Add("Måned", typeof(string));
dt.Columns.Add("Betaling (brutto)", typeof(decimal));
dt.Columns.Add("Betaling (netto)", typeof(decimal));
dt.Columns.Add("Bestillingsgebyr (netto)", typeof(decimal));
dt.Columns.Add("Betalingsgebyr (netto)", typeof(decimal));
dt.Columns.Add("OppdragsMVAkode", typeof(decimal));
dt.Columns.Add("LøyvehaverFakturaID", typeof(string));
dt.Columns.Add("Oppdragsgebyr (netto)", typeof(decimal));
dt.Columns.Add("OppdragsgebyrMVAkode", typeof(decimal));
dt.Columns.Add("RidelRegionFakturaID", typeof(string));
IXLRow currentRow;
for (int dtRow = 0; dtRow < br_Row - tl_Row; dtRow++) {
currentRow = ws.Row(tl_Row + dtRow + 1);
dt.Rows.Add();
for (int dtCol = 0; dtCol < br_Col - tl_Col + 1; dtCol++) {
dt.Rows[dtRow][dtCol] = currentRow.Cell(tl_Col + dtCol).Value;
}
}
return dt;
}
}
As far as I can see, all my column types match, as well as their order.
I changed all my types to nvarchar, and the code "works".
But someone smarter than me told me it was not a good idea to fake the column types.
What am I missing?
To pass a null value, you need to set the column value as DBNull.Value. You can set DBNull like this
dt.Rows[dtRow][dtCol] = currentRow.Cell(tl_Col + dtCol).Value ?? (object)DBNull.Value;
You must also set SqlDBType TypeName and Direction properties
cmd.Parameters.Add(
new SqlParameter("#trips", SqlDBType.Structured)
{
TypeName = "dbo.udtTripsPerMonth",
Direction = ParameterDirection.Input,
Value = dt
});
I am trying to write a C# program (.Net core 2.1) to read all the check constraints for a given table from ms sql server database. I am using sys.check_constraints table to get this information, when I tried to read this using ado.net datareader the column 'definition' from this table is always coming as empty though it has value.
SQL Script (DDL, Stored Proc to Get CheckConstraints, Exec state of Stored Proc)
GO
/****** Object: Table [dbo].[Customer] Script Date: 7/10/2019 3:24:22 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Customer](
[Id] [bigint] IDENTITY(1,1) NOT NULL,
[CompanyId] [smallint] NOT NULL,
[Prefix] [varchar](4) NOT NULL,
[FirstName] [varchar](50) NOT NULL,
[LastName] [varchar](50) NOT NULL,
[MiddleName] [varchar](50) NULL,
[Suffix] [varchar](4) NULL,
[NickName] [varchar](10) NULL,
[ProfilePictureName] [varchar](50) NULL,
[Company] [varchar](100) NULL,
[DateOfBirth] [date] NOT NULL,
[DateOfDeath] [date] NULL,
[Gender] [char](1) NOT NULL,
[Type] [varchar](10) NOT NULL,
[IsActive] [char](1) NULL,
[CreatedBy] [varchar](50) NOT NULL,
[CreatedOn] [datetime2](7) NOT NULL,
[UpdatedBy] [varchar](50) NULL,
[UpdatedOn] [datetime2](7) NULL,
[Process] [varchar](100) NULL,
[MessageId] [varchar](50) NOT NULL,
[SysStartDate] [datetime2](2) GENERATED ALWAYS AS ROW START NOT NULL,
[SysEndDate] [datetime2](2) GENERATED ALWAYS AS ROW END NOT NULL,
CONSTRAINT [PK_CUSTOMER] PRIMARY KEY CLUSTERED
(
[Id] ASC,
[CompanyId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
PERIOD FOR SYSTEM_TIME ([SysStartDate], [SysEndDate])
) ON [PRIMARY]
WITH
(
SYSTEM_VERSIONING = ON ( HISTORY_TABLE = [dbo].[MSSQL_TemporalHistoryFor_601769201] )
)
GO
ALTER TABLE [dbo].[Customer] ADD DEFAULT ('Y') FOR [IsActive]
GO
ALTER TABLE [dbo].[Customer] WITH CHECK ADD CONSTRAINT [CUSTOMER_PREFIX_CHECK] CHECK (([Prefix]='Dr' OR [Prefix]='Miss' OR [Prefix]='Ms' OR [Prefix]='Mrs' OR [Prefix]='Mr'))
GO
ALTER TABLE [dbo].[Customer] CHECK CONSTRAINT [CUSTOMER_PREFIX_CHECK]
GO
ALTER TABLE [dbo].[Customer] WITH CHECK ADD CONSTRAINT [CUSTOMER_SUFFIX_CHECK] CHECK (([Suffix]='RN' OR [Suffix]='MD' OR [Suffix]='ESQ' OR [Suffix]='DO' OR [Suffix]='DDS' OR [Suffix]='DDM' OR [Suffix]='III' OR [Suffix]='II' OR [Suffix]='I' OR [Suffix]='Sr' OR [Suffix]='Jr'))
GO
ALTER TABLE [dbo].[Customer] CHECK CONSTRAINT [CUSTOMER_SUFFIX_CHECK]
GO
ALTER TABLE [dbo].[Customer] WITH CHECK ADD CONSTRAINT [CUSTOMER_TYPE_CHECK] CHECK (([Type]='Customer' OR [Type]='VENDOR' OR [Type]='INSIDER' OR [Type]='ANALYST' OR [Type]='INVESTOR'))
GO
ALTER TABLE [dbo].[Customer] CHECK CONSTRAINT [CUSTOMER_TYPE_CHECK]
GO
CREATE PROCEDURE [dbo].[GetCheckConstraints_Dup](#tableName as varchar(200))
AS
BEGIN
select
col.[name] as column_name,
con.[definition] As [constraint_value]
from sys.check_constraints con
left outer join sys.objects t
on con.parent_object_id = t.object_id
left outer join sys.all_columns col
on con.parent_column_id = col.column_id
and con.parent_object_id = col.object_id
where t.[name]=#tableName and con.is_disabled=0
order by con.name;
End;
GO
exec GetCheckConstraints_Dup 'Customer'
SQL Server Result
C#
public static List<Constraints> GetConstraints(string tableName,string connectionString)
{
var constraints = new List<Constraints>();
using (SqlConnection connection = new SqlConnection(connectionString))
{
//SqlDataReader
connection.Open();
SqlCommand cmd = new SqlCommand("DBO.GetCheckConstraints_Dup", connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#tableName", SqlDbType.VarChar).Value = tableName;
using (SqlDataReader dataReader = cmd.ExecuteReader())
{
while (dataReader.Read())
{
constraints.Add(new Constraints() { FieldName = dataReader["column_name"].ToString(), Constraint = ConstraintType.Check, ConstraintValue = dataReader["constraint_value"].ToString() });
}
}
}
return constraints;
}
No repro for me. Does this repro?
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApp18
{
class Program
{
static string ddl = #"
GO
--if exists (select * from sys.tables where name = 'Customer')
-- begin
-- ALTER TABLE [dbo].[Customer] SET ( SYSTEM_VERSIONING = OFF)
-- DROP TABLE [dbo].[Customer]
-- DROP TABLE [dbo].[MSSQL_TemporalHistoryFor_601769201]
--end
go
/****** Object: Table [dbo].[Customer] Script Date: 7/10/2019 3:24:22 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Customer](
[Id] [bigint] IDENTITY(1,1) NOT NULL,
[CompanyId] [smallint] NOT NULL,
[Prefix] [varchar](4) NOT NULL,
[FirstName] [varchar](50) NOT NULL,
[LastName] [varchar](50) NOT NULL,
[MiddleName] [varchar](50) NULL,
[Suffix] [varchar](4) NULL,
[NickName] [varchar](10) NULL,
[ProfilePictureName] [varchar](50) NULL,
[Company] [varchar](100) NULL,
[DateOfBirth] [date] NOT NULL,
[DateOfDeath] [date] NULL,
[Gender] [char](1) NOT NULL,
[Type] [varchar](10) NOT NULL,
[IsActive] [char](1) NULL,
[CreatedBy] [varchar](50) NOT NULL,
[CreatedOn] [datetime2](7) NOT NULL,
[UpdatedBy] [varchar](50) NULL,
[UpdatedOn] [datetime2](7) NULL,
[Process] [varchar](100) NULL,
[MessageId] [varchar](50) NOT NULL,
[SysStartDate] [datetime2](2) GENERATED ALWAYS AS ROW START NOT NULL,
[SysEndDate] [datetime2](2) GENERATED ALWAYS AS ROW END NOT NULL,
CONSTRAINT [PK_CUSTOMER] PRIMARY KEY CLUSTERED
(
[Id] ASC,
[CompanyId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY],
PERIOD FOR SYSTEM_TIME ([SysStartDate], [SysEndDate])
) ON [PRIMARY]
WITH
(
SYSTEM_VERSIONING = ON ( HISTORY_TABLE = [dbo].[MSSQL_TemporalHistoryFor_601769201] )
)
GO
ALTER TABLE [dbo].[Customer] ADD DEFAULT ('Y') FOR [IsActive]
GO
ALTER TABLE [dbo].[Customer] WITH CHECK ADD CONSTRAINT [CUSTOMER_PREFIX_CHECK] CHECK (([Prefix]='Dr' OR [Prefix]='Miss' OR [Prefix]='Ms' OR [Prefix]='Mrs' OR [Prefix]='Mr'))
GO
ALTER TABLE [dbo].[Customer] CHECK CONSTRAINT [CUSTOMER_PREFIX_CHECK]
GO
ALTER TABLE [dbo].[Customer] WITH CHECK ADD CONSTRAINT [CUSTOMER_SUFFIX_CHECK] CHECK (([Suffix]='RN' OR [Suffix]='MD' OR [Suffix]='ESQ' OR [Suffix]='DO' OR [Suffix]='DDS' OR [Suffix]='DDM' OR [Suffix]='III' OR [Suffix]='II' OR [Suffix]='I' OR [Suffix]='Sr' OR [Suffix]='Jr'))
GO
ALTER TABLE [dbo].[Customer] CHECK CONSTRAINT [CUSTOMER_SUFFIX_CHECK]
GO
ALTER TABLE [dbo].[Customer] WITH CHECK ADD CONSTRAINT [CUSTOMER_TYPE_CHECK] CHECK (([Type]='Customer' OR [Type]='VENDOR' OR [Type]='INSIDER' OR [Type]='ANALYST' OR [Type]='INVESTOR'))
GO
ALTER TABLE [dbo].[Customer] CHECK CONSTRAINT [CUSTOMER_TYPE_CHECK]
GO
CREATE OR ALTER PROCEDURE [dbo].[GetCheckConstraints_Dup](#tableName as varchar(200))
AS
BEGIN
select
col.[name] as column_name,
con.[definition] As [constraint_value]
from sys.check_constraints con
left outer join sys.objects t
on con.parent_object_id = t.object_id
left outer join sys.all_columns col
on con.parent_column_id = col.column_id
and con.parent_object_id = col.object_id
where t.[name]=#tableName and con.is_disabled=0
order by con.name;
End;
GO
";
static IEnumerable<string> GetBatches(string script)
{
var rdr = new System.IO.StringReader(script);
var sb = new StringBuilder();
while (true)
{
var l = rdr.ReadLine()?.Trim();
if (l == null)
{
var batch = sb.ToString().Trim();
if (batch.Length > 0)
yield return sb.ToString();
break;
}
else if (l.Equals( "GO", StringComparison.OrdinalIgnoreCase))
{
var batch = sb.ToString().Trim();
if (batch.Length > 0)
yield return sb.ToString();
sb.Clear();
}
else
{
sb.AppendLine(l.Trim());
}
}
}
static void Main(string[] args)
{
var constr = "Server=localhost;database=tempdb;integrated security=true";
using (var con = new SqlConnection(constr))
{
con.Open();
foreach (var batch in GetBatches(ddl))
{
var cmd = con.CreateCommand();
cmd.CommandText = batch;
cmd.ExecuteNonQuery();
}
var constraints = GetConstraints("Customer", constr);
foreach (var constraint in constraints)
{
Console.WriteLine($"{constraint.FieldName} {constraint.ConstraintValue}");
}
}
Console.WriteLine("Hit any key to exit");
Console.ReadKey();
}
public static List<Constraints> GetConstraints(string tableName, string connectionString)
{
var constraints = new List<Constraints>();
using (SqlConnection connection = new SqlConnection(connectionString))
{
//SqlDataReader
connection.Open();
SqlCommand cmd = new SqlCommand("DBO.GetCheckConstraints_Dup", connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#tableName", SqlDbType.VarChar).Value = tableName;
using (SqlDataReader dataReader = cmd.ExecuteReader())
{
while (dataReader.Read())
{
constraints.Add(new Constraints() { FieldName = dataReader["column_name"].ToString(), Constraint = "Check", ConstraintValue = dataReader["constraint_value"].ToString() });
}
}
}
return constraints;
}
public class Constraints
{
public string FieldName { get; internal set; }
public string Constraint { get; internal set; }
public string ConstraintValue { get; internal set; }
}
}
}
I would like to insert a record into my RDV Table.
This is the query creation of my table
CREATE TABLE [dbo].[RDV] (
[idRdv] INT NOT NULL,
[objet] NVARCHAR (50) NULL,
[objectif] NVARCHAR (50) NULL,
[DateRdv] DATETIME NULL,
[commentaire] NVARCHAR (50) NULL,
[archive] NVARCHAR (50) NULL,
[idClient] INT NULL,
[idUser] INT NULL,
[idResultat] INT NULL,
CONSTRAINT [PK_RDV] PRIMARY KEY CLUSTERED ([idRdv] ASC),
FOREIGN KEY ([idClient]) REFERENCES [dbo].[Client] ([idClient]),
FOREIGN KEY ([idUser]) REFERENCES [dbo].[User] ([idUser]),
FOREIGN KEY ([idResultat]) REFERENCES [dbo].[Resultat] ([idResultat]);
and this is my code of insert
public RDV()
{
InitializeComponent();
textBox3.Visible = false;
label7.Visible = false;
}
private void btnAdd_Click(object sender, EventArgs e)
{
Random rdm = new Random();
int num = rdm.Next(5, 2000);
textBox3.Text = num.ToString();
string cmdStr = "Insert into RDV (idRdv,idUser,idClient,objet,objectif,DateRdv,commentaire) select #idRdv,#idUser,#idClient,#objet,#objectif,#DateRdv,#commentaire from RDV, Client, [User] where RDV.idClient = Client.idClient and RDV.idUser = [User].idUser ";
SqlConnection con = new SqlConnection("Data Source=ADMIN-PC\\SQLEXPRESS;Initial Catalog=timar;Integrated Security=True");
SqlCommand cmd = new SqlCommand(cmdStr, con);
cmd.Parameters.AddWithValue("#idRdv", textBox3.Text);
cmd.Parameters.AddWithValue("#idUser", (comboBox1.SelectedValue));
cmd.Parameters.AddWithValue("#idClient", (comboBox2.SelectedValue));
cmd.Parameters.AddWithValue("#objet", textBox1.Text);
cmd.Parameters.AddWithValue("#objectif", textBox2.Text);
cmd.Parameters.AddWithValue("#DateRdv", dateTimePicker1.Value.ToString());
cmd.Parameters.AddWithValue("#commentaire", textBox4.Text);
con.Open();
int LA = cmd.ExecuteNonQuery();
Console.WriteLine("Ligne ajoutée: {0}", LA);
And,the field idRdv , i want to add it but should be hidden and Random like in the code above.
When , I run my project , it shows me an error Violation of PRIMARY KEY " PK_RDV ". Can not insert duplicate key in object ' dbo.RDV ". Value of Duplicate Key:1505 (this the value of idRdv)
Pleaaaaseee, help me. How should I correct it.
Thanks in advance
You are using the ID with Random. As your table ID column is containing Primary Key Constraint it may get this error.
Either you check that the random number generated is not exist in the table before insert. Or use a method to get Max(ID)+1 and set this as new ID
I have researched this and apologize if this is duplicate, but I cant seem to find the correct answer, and I learn so much from this site.
I have 3 tables:
CREATE TABLE [Reporting].[ReportingCompanies](
[ID] [int] IDENTITY(1,1) NOT NULL,
[EINC] [int] NOT NULL,
[CompanyId] [varchar](4) NOT NULL,
[CompanyName] [varchar](50) NOT NULL,
[LastClosedWeek] [datetime] NOT NULL,
[PriorWeekSales] [decimal](14, 4) NULL,
[PriorWeek] [datetime] NULL,
[CurrentWeek] [datetime] NULL,
[LastWeekSales] [decimal](14, 4) NULL,
[AgingBalance] [decimal](14, 4) NULL,
[DataAsOf] [datetime] NULL,
[Tier] [int] NULL,
[CurrentWeeklyAverage] [decimal](14, 4) NULL,
[AvgAged] [decimal](14, 4) NULL,
[hasSpread] [bit] NULL,
[DSO] [int] NULL,
[isFamily] [bit] NULL,
[ImportStatus] [bit] NULL,
[ClientStatus] [varchar](50) NULL,
CONSTRAINT [PK_ReportingCompanies] 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]
CREATE TABLE [Reporting].[AllowedCompanies](
[ID] [int] IDENTITY(1,1) NOT NULL,
[CustomUserProfileUserId] [uniqueidentifier] NOT NULL,
[CustomUserProfileID] [int] NOT NULL,
[ReportingCompanyID] [int] NOT NULL,
CONSTRAINT [PK_AllowedCompanies] 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]
CREATE TABLE [Reporting].[CustomUserProfiles](
[ID] [int] IDENTITY(1,1) NOT NULL,
[ApplicationId] [uniqueidentifier] NOT NULL,
[UserId] [uniqueidentifier] NOT NULL,
[UserName] [nvarchar](256) NOT NULL,
[LoweredUserName] [nvarchar](256) NOT NULL,
[MobileAlias] [nvarchar](16) NULL,
[IsAnonymous] [bit] NOT NULL,
[LastActivityDate] [datetime] NOT NULL,
[ImportStatus] [bit] NULL,
CONSTRAINT [PK_CustomUserProfiles] PRIMARY KEY CLUSTERED
(
[UserId] ASC,
[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]
I now need to add a 4th table using a left outer join, to only get a default value of 0 for the VisitCount column if no records exist.
CREATE TABLE [PayJot].[FavoriteClients](
[FavRowID] [int] IDENTITY(1,1) NOT NULL,
[Userid] [uniqueidentifier] NOT NULL,
[CompanyId] [int] NOT NULL,
[VisitCount] [int] NOT NULL,
CONSTRAINT [PK_FavoriteClients] PRIMARY KEY CLUSTERED
(
[FavRowID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
Here is my latest attempt which returns the error "The entity or complex type 'DALModel.FavoriteClient' cannot be constructed in a LINQ to Entities query" but that's exactly what intellisense seems to be asking for (?)
var userName = HttpContext.Current.User.Identity.Name;
var q = from c in db.ReportingCompanies1
join a in db.AllowedCompanies on new { ID = (int)c.ID } equals new { ID = a.ReportingCompanyID }
join p in db.CustomUserProfiles on new { CustomUserProfileID = a.CustomUserProfileID } equals new { CustomUserProfileID = p.ID }
join f in db.FavoriteClients on new { A = c.ID, B = p.UserId } equals new { A = f.CompanyId, B = f.Userid } into fvc
from userfavs in fvc.DefaultIfEmpty(new FavoriteClient { CompanyId = c.ID, Userid = p.UserId , VisitCount = 0 })
where
p.UserName == userName
orderby c.CompanyName
select new Clients()
{
ID = c.ID,
CompanyId = c.CompanyId,
CompanyName = c.CompanyName,
visitCount = userfavs.VisitCount
};
ObservableCollection<Clients> clientList = new ObservableCollection<Clients>(q.ToList());
I am fairly new to Linq and while all the examples I have read make sense as explained, they fail miserably in implementation. Please advise if you can and thanx in advance.
I just got it working:
var q = from p in db.CustomUserProfiles
join a in db.AllowedCompanies on new { ID = p.ID } equals new { ID = a.CustomUserProfileID }
join c in db.ReportingCompanies1 on new { ReportingCompanyID = (int)(int)a.ReportingCompanyID } equals new { ReportingCompanyID = c.ID }
join f in db.FavoriteClients
on new { a.CustomUserProfileUserId, ReportingCompanyID = a.ReportingCompanyID }
equals new { CustomUserProfileUserId = (Guid)f.Userid, ReportingCompanyID = f.CompanyId } into FavoriteClients_join
from FavoriteClients in FavoriteClients_join.DefaultIfEmpty()
where
p.UserName == userName
orderby
FavoriteClients.VisitCount descending,
c.CompanyName
select new Clients()
{
ID = c.ID,
CompanyId = c.CompanyId,
CompanyName = c.CompanyName,
visitCount = ((Int32?)FavoriteClients.VisitCount ?? (Int32)0)
};
I am making a gym management system and I am using foreign keys in my tables. Everything was working perfectly, but after I added foreign keys I am getting the following error:
SQLException was Unhandled
The INSERT statement conflicted with the FOREIGN KEY constraint
"FK_member_info_instructor_info". The conflict occurred in database "D:\GYM MANAGEMENT
SYSTEM\GYM MANAGEMENT SYSTEM\BIN\DEBUG\GMSDATABASE.MDF", table "dbo.instructor_info",
column 'InstructorID'.
The statement has been terminated.
This error is pointing to this code:
public void UpdateDatabase(System.Data.DataSet ds)
{
System.Data.SqlClient.SqlCommandBuilder cb = new
System.Data.SqlClient.SqlCommandBuilder(da_1);
cb.DataAdapter.Update(ds.Tables[0]);
}
The above code is in my database collection class which is as following:
class GMSDConnectionClass
{
System.Data.SqlClient.SqlDataAdapter da_1;
System.Data.SqlClient.SqlConnection con;
public string sql_string;
public string strCon;
public string Sql
{
set { sql_string = value; }
}
public string connection_string
{
set { strCon = value; }
}
public System.Data.DataSet GetConnection
{
get { return MyDataSet(); }
}
public System.Data.DataSet MyDataSet()
{
con = new System.Data.SqlClient.SqlConnection(strCon);
con.Open();
da_1 = new System.Data.SqlClient.SqlDataAdapter(sql_string, con);
System.Data.DataSet dat_set = new System.Data.DataSet();
da_1.Fill(dat_set, "Table_data_1");
con.Close();
return dat_set;
}
public void UpdateDatabase(System.Data.DataSet ds)
{
System.Data.SqlClient.SqlCommandBuilder cb = new
System.Data.SqlClient.SqlCommandBuilder(da_1);
cb.DataAdapter.Update(ds.Tables[0]);
}
}
These are my tables which are being used when the error is thrown:
instructor_info table:
CREATE TABLE [dbo].[instructor_info] (
[InstructorID] INT IDENTITY (1, 1) NOT NULL,
[instructor] NVARCHAR (50) NOT NULL,
[father_name] NVARCHAR (50) NULL,
[age] NCHAR (10) NULL,
[address] NVARCHAR (MAX) NULL,
[contact] NVARCHAR (50) NULL,
[height] NCHAR (10) NULL,
[weight] NCHAR (10) NULL,
[chest] NCHAR (10) NULL,
[triceps_biceps] NCHAR (10) NULL,
[waist] NCHAR (10) NULL,
[shoulders] NCHAR (10) NULL,
[thighs] NCHAR (10) NULL,
[calves] NCHAR (10) NULL,
[memberID] INT NULL,
[date_of_admission] DATE NULL,
[photo] IMAGE NULL,
PRIMARY KEY CLUSTERED ([InstructorID] ASC),
CONSTRAINT [FK_instructor_info_member_info] FOREIGN KEY ([memberID]) REFERENCES [dbo].
[member_info] ([memberID])
);
member_info table:
CREATE TABLE [dbo].[member_info] (
[memberID] INT IDENTITY (1, 1) NOT NULL,
[memberName] NVARCHAR (50) NULL,
[father_name] NVARCHAR (50) NULL,
[age] NCHAR (10) NULL,
[address] NVARCHAR (50) NULL,
[contact] NVARCHAR (50) NULL,
[height] NVARCHAR (50) NULL,
[weight] NVARCHAR (50) NULL,
[chest] NVARCHAR (50) NULL,
[triceps_biceps] NVARCHAR (50) NULL,
[waist] NVARCHAR (50) NULL,
[shoulders] NVARCHAR (50) NULL,
[thighs] NVARCHAR (50) NULL,
[calves] NVARCHAR (50) NULL,
[instructorID] INT NULL,
[date_of_admission] DATE NULL,
[photo] IMAGE NULL,
PRIMARY KEY CLUSTERED ([memberID] ASC),
CONSTRAINT [FK_member_info_instructor_info] FOREIGN KEY ([instructorID]) REFERENCES
[dbo].[instructor_info] ([InstructorID])
);
This is my code for the save button on my form:
private void saveBtn_Click(object sender, EventArgs e)
{
DataRow row = memberDataS.Tables[0].NewRow();
row[0] = maxRowsMember + 1;
row[1] = memberName.Text;
row[2] = fatherName.Text;
row[3] = age.Text;
row[4] = address.Text;
row[5] = contact.Text;
row[6] = height.Text;
row[7] = weight.Text;
row[8] = chest.Text;
row[9] = tricepBicep.Text;
row[10] = waist.Text;
row[11] = shoulders.Text;
row[12] = thighs.Text;
row[13] = calves.Text;
row[14] = int.Parse(instructor.Text);
row[15] = dateTimePicker1.Text;
memberDataS.Tables[0].Rows.Add(row);
memberString.UpdateDatabase(memberDataS);
maxRowsMember += 1;
inc = maxRowsMember - 1;
MessageBox.Show("Database updated");
cancelBtn.Enabled = false;
saveBtn.Enabled = false;
addNewMemberBtn.Enabled = true;
}
All help will be appreciated. Thanks a lot.
I believe that your error may be resulting from row 14:
row[14] = int.Parse(instructor.Text);
If my assumption about your code is correct, the instructor variable contains the VARCHAR(50) instructor name, not the INT IDENTITY value of instructorID.