Left outer join Linq to Entities with MVC model - c#

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

Related

SQL/C#: DataTable to stored procedure (INSERT from user-defined table type) - Converting error

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

SqlBulkCopy Identity on SQL SERVER

I tried insert to database with SqlBulkCopy but problem is when id on Sql server is identity(1,1)
I have got this error "Cannot insert the value NULL into column 'two', table 'mydb.dbo.test'; column does not allow nulls. INSERT fails."
string connString = string.Format("Data Source={0};Initial Catalog={1};Integrated Security=True",DbServer,databaseName);
DataTable table = new DataTable("test");
//table.Columns.Add("id");
table.Columns.Add("one", typeof(int));
table.Columns.Add("two", typeof(int));
DataRow row = table.NewRow();
row["one"] = 1;
row["two"] = 2;
table.Rows.Add(row);
DataRow row2 = table.NewRow();
row2["one"] = 1;
row2["two"] = 2;
table.Rows.Add(row2);
SqlBulkCopy bulk = new SqlBulkCopy(connString);
bulk.DestinationTableName = "test";
try
{
bulk.WriteToServer(table);
bulk.Close();
}
catch (Exception ex)
{
Console.WriteLine("error. {0}", ex.Message);
}
finally
{
bulk.Close();
}
edit table scheme:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[test](
[id] [INT] IDENTITY(1,1) NOT NULL,
[one] [INT] NOT NULL,
[two] [INT] NOT NULL,
CONSTRAINT [PK_test] 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
If your local table definition does not match the server's (it is missing the identity column), then you need to add an explicit mapping for each column (case-sensitive)
The first value is the name of the local source column, the second is destination column name.
bulk.ColumnMappings.Add("one", "one");
bulk.ColumnMappings.Add("two", "two");
This is also the case if the names don't match up exactly.

definition column from sys.check_constraints is coming as null in ado.net datareader when the field is not null when executed from sssms

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; }
}
}
}

Trying to write regex that matches [ID] = 'anynumber'

I'm trying to write a regex that matches the substring "[ID] = '#number'".
this is part of the string that I mean:
[Patient.ID] = 123 And [Zorgtraject] = 123 And [Activiteit] Is Null Or [ID] = '86777' Or [ID] = '86778' Or [ID] = '86779' Or [ID] = '86780' Or [ID] = '86781' Or [ID] = '86782' Or [ID] = '86783' Or [ID] = '86784' Or [ID] = '86785' Or [ID] = '86786' Or [ID] = '86787' Or [ID] = '86788' Or [ID] = '86789' Or [ID] = '86790' Or [ID] = '86791' Or [ID] = '86792' Or [ID] = '86793' Or [ID] = '86794' Or [ID] = '86795' Or [ID] = '86796' Or [ID] = '86797' Or [ID] = '86798' Or [ID] = '86799' Or [ID] = '86800' Or [ID] = '86801' Or [ID] = '86802' Or [ID] = '86803' Or [ID] = '86804' Or [ID] = '86805' Or [ID] = '86806' Or [ID] = '86807' Or [ID] = '86808' Or [ID] = '86809' Or [ID] = '86810' Or [ID] = '86811' Or [ID] = '86812' Or [ID] = '86813' Or [ID] = '86814' Or [ID] = '86815' Or [ID] = '86816' Or [ID] = '86817' Or [ID] = '86818' Or [ID] = '86819' Or [ID] = '86820' Or [ID] = '86821' Or [ID] = '86822' Or [ID] = '86823' Or [ID] = '86824' Or [ID] = '86825' Or [ID] = '86826' Or [ID] = '86827' Or [ID] = '86828' Or [ID] = '86829' Or [ID] = '86830' Or [ID] = '86831' Or [ID] = '86832' Or [ID] = '86833' Or [ID] = '86834' Or [ID] = '86835' Or [ID] = '86836' Or [ID] = '86837' Or [ID] = '86838' Or [ID] = '86839' Or [ID] = '86840' Or [ID] = '86841' Or [ID] = '86842' Or [ID] = '86843' Or [ID] = '86844' Or [ID] = '86845' Or [ID] = '86846' Or [ID] = '86847'
I've gotten this far: [\[ID\] = '{\d+:\d+}'] but that matches really strangely like it also grabs the [ and ID] from Patient.ID.
all I want is a regex that makes a substring like [ID] = '86845'
Thank you in advance.
You may use
\[ID]\s*=\s*'\d+'
See the regex demo
Details
\[ID] - [ID] substring
\s*=\s* - a = enclosed with 0+ whitespace chars
' - a single quotation mark
\d+ - 1+ digits
' - a single quotation mark
Regulex graph:
C#:
var results = Regex.Matches(s, #"\[ID]\s*=\s*'\d+'")
.Cast<Match>()
.Select(x => x.Value)
.ToList();
To only get the numbers use
var results = Regex.Matches(s, #"\[ID]\s*=\s*'(\d+)'")
.Cast<Match>()
.Select(x => x.Groups[1].Value)
.ToList();

Select data from two tables with Linq/Lambda

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

Categories