Composite Primary Key having column with Allow Null true - composite-key

I would like to know the best practice.
I have a table Committee, Application, EmpInternal and EmpExternal
The primary key of Committee is a composite Key comprising of ApplicationID, EmpInternalID and EmpExternalID
Now since, AllowNull property is not allowed to be true in a column in composite key. What should I do to store committee members in Committee table which are sometimes Internal and external. All the columns ApplicationID, EmpInternalID and EmpExternalID are autonumber in their respective tables
CREATE TABLE [dbo].[Employee](
[EmployeeID] [varchar](10) NOT NULL,
[UserID] [varchar](100) NULL,
[Title] [varchar](50) NULL,
[Name] [nvarchar](240) NULL,
[Rank] [varchar](150) NULL,
[Department] [varchar](240) NULL,
[College] [varchar](240) NULL,
[POBox] [varchar](120) NULL,
[Phone] [varchar](60) NULL,
[JoinDate] [varchar](200) NULL,
CONSTRAINT [PK_Employee1] 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])
CREATE TABLE [dbo].[EmployeeExternal](
[EmployeeExID] [varchar](10) NOT NULL,
[Title] [nvarchar](50) NULL,
[Name] [nvarchar](50) NULL,
[Rank] [nvarchar](50) NULL,
[Department] [nvarchar](4000) NULL,
[Organization] [nvarchar](4000) NULL,
[Address] [nvarchar](4000) NULL,
[Email] [nvarchar](50) NULL,
[Email2] [nvarchar](50) NULL,
[Phone] [nvarchar](50) NULL,
[Mobile] [nvarchar](50) NULL,
[Country] [nvarchar](50) NULL,
CONSTRAINT [PK_Employee1] PRIMARY KEY CLUSTERED
( [EmployeeExID] ASC )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY])

A flag record in the Employee table and EmployeeExternal table is a better solution than merging these two tables. the key of flagged record in the composite key remove the use of null in the composite key

Related

How to make Identity use of MVC instead of razor pages in asp.net core 2.2

Since asp.net core 2.1 the MVC is not supported as default model with Identity. I want to run Identity with MVC in asp.net core 2.2
Make a long story short. This is a asp.net 4.6.2 site with local db that I want upgrade to asp.net core 2.2 . I thought that this would be simple thing. So wrong I was. So what did I do:
Created an new ASP.net core 2.0 project with local Identity
Scaffolded the ef context with database first with Scaffold-DbContext
Fixed so EF is loaded correctly in Startup.
Removed aspnetusers, aspnetuserroles, aspnetuserlogin, aspnetroles models from generated scaffold by the Scaffold-Dbcontext
Updated ApplicationDbContext to inherits from IdentityDbContext. ApplicationUser inherits from IdentityUser
After I faked that the migration have been applied, I manually added following columns in aspnetusers
6.1 ConcurrencyStamp
6.2 NormalizedUserName
6.3 NormalizedEmail
6.4 Changed name LockoutEnd? to LockoutEnd
The system builds but still I cant get it to use the Account controller. I have followed the steps in https://learn.microsoft.com/en-us/aspnet/core/security/authentication/scaffold-identity?view=aspnetcore-2.2
without no avail. It seems what I do I can't get it to read the mvc controller even after I scaffolded the Identity.
I think the difference in implementations of Identity in asp.net core 2.X Identity is either to high or to narrow regarding earlier implementations.
Included part of my startup
services.Configure<CookiePolicyOptions>(options =>
{
// This lambda determines whether user consent for non-essential cookies is needed for a given request.
options.CheckConsentNeeded = context => true;
options.MinimumSameSitePolicy = SameSiteMode.None;
});
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(
Configuration.GetConnectionString("DefaultConnection")));
services.AddIdentity<ApplicationUser, IdentityRole>()
// services.AddDefaultIdentity<IdentityUser>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
.AddRazorPagesOptions(options =>
{
options.AllowAreas = true;
//options.Conventions.AuthorizeAreaFolder("Identity", "/Account/Manage");
//options.Conventions.AuthorizeAreaPage("Identity", "/Account/Logout");
});
services.ConfigureApplicationCookie(options =>
{
options.LoginPath = $"/Account/Login";
options.LogoutPath = $"/Account/Logout";
options.AccessDeniedPath = $"/Account/AccessDenied";
});
// using Microsoft.AspNetCore.Identity.UI.Services;
services.AddSingleton<IEmailSender, EmailSender>();
}
I want to use MVC with Identity Core 2.2 with an old database from Identity .Net.
So any suggestions?
It's not clear what you're doing exactly, but it sounds like you've scaffolded the Identity Razor Pages into your project. If that's the case, those are going to take precedent over your controller, since it's a more physical route.
All the other code looks good. You're using AddIdentity instead of AddDefaultIdentity (so the default UI is not included). Assuming you've actually created an AccountController and your routing is set up correctly, then it should work, as long as you don't have the default UI physically scaffolded into your project.
Recently I have done the same thing. The following might help you. First create equivalent Application tables for all AspNet tables. The MS SQL Server script below will create:
dbo.ApplicationRole
dbo.ApplicationRoleClaim
dbo.ApplicationUser
dbo.ApplicationUserClaim
dbo.ApplicationUserLogin
dbo.ApplicationUserRole
dbo.ApplicationUserToken
Open MS SQL Server Management Studio
Select your database
Start a new query
Run the script below and replace YOUR_DATABASE with the name of your database
Next you should copy the contents of your soon obsolete AspNet tables into the new Application tables. In this process you should also handle the change from datatype nvarchar to int for UserId and RoleId.
USE [YOUR_DATABASE]
GO
/****** Object: Table [dbo].[ApplicationRole] Script Date: 24-May-21 9:44:46 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ApplicationRole](
[Id] [int] NOT NULL,
[Name] [nvarchar](256) NULL,
[NormalizedName] [nvarchar](256) NULL,
[ConcurrencyStamp] [nvarchar](max) NULL,
CONSTRAINT [PK_ApplicationRoles] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object: Table [dbo].[ApplicationRoleClaim] Script Date: 24-May-21 9:44:46 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ApplicationRoleClaim](
[Id] [int] IDENTITY(1,1) NOT NULL,
[RoleId] [int] NOT NULL,
[ClaimType] [nvarchar](max) NULL,
[ClaimValue] [nvarchar](max) NULL,
CONSTRAINT [PK_ApplicationRoleClaims] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object: Table [dbo].[ApplicationUser] Script Date: 24-May-21 9:44:46 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ApplicationUser](
[Id] [int] NOT NULL,
[UserName] [nvarchar](256) NULL,
[NormalizedUserName] [nvarchar](256) NULL,
[Email] [nvarchar](256) NULL,
[NormalizedEmail] [nvarchar](256) NULL,
[EmailConfirmed] [bit] NOT NULL,
[PasswordHash] [nvarchar](max) NULL,
[SecurityStamp] [nvarchar](max) NULL,
[ConcurrencyStamp] [nvarchar](max) NULL,
[PhoneNumber] [nvarchar](max) NULL,
[PhoneNumberConfirmed] [bit] NOT NULL,
[TwoFactorEnabled] [bit] NOT NULL,
[LockoutEnd] [datetimeoffset](7) NULL,
[LockoutEnabled] [bit] NOT NULL,
[AccessFailedCount] [int] NOT NULL,
CONSTRAINT [PK_ApplicationUsers] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object: Table [dbo].[ApplicationUserClaim] Script Date: 24-May-21 9:44:46 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ApplicationUserClaim](
[Id] [int] IDENTITY(1,1) NOT NULL,
[UserId] [int] NOT NULL,
[ClaimType] [nvarchar](max) NULL,
[ClaimValue] [nvarchar](max) NULL,
CONSTRAINT [PK_ApplicationUserClaims] PRIMARY KEY CLUSTERED
(
[Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object: Table [dbo].[ApplicationUserLogin] Script Date: 24-May-21 9:44:46 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ApplicationUserLogin](
[LoginProvider] [nvarchar](128) NOT NULL,
[ProviderKey] [nvarchar](128) NOT NULL,
[ProviderDisplayName] [nvarchar](max) NULL,
[UserId] [int] NOT NULL,
CONSTRAINT [PK_ApplicationUserLogins] PRIMARY KEY CLUSTERED
(
[LoginProvider] ASC,
[ProviderKey] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
/****** Object: Table [dbo].[ApplicationUserRole] Script Date: 24-May-21 9:44:46 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ApplicationUserRole](
[UserId] [int] NOT NULL,
[RoleId] [int] NOT NULL,
CONSTRAINT [PK_ApplicationUserRole] PRIMARY KEY CLUSTERED
(
[UserId] ASC,
[RoleId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[ApplicationUserToken] Script Date: 24-May-21 9:44:46 AM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[ApplicationUserToken](
[UserId] [int] NOT NULL,
[LoginProvider] [nvarchar](128) NOT NULL,
[Name] [nvarchar](128) NOT NULL,
[Value] [nvarchar](max) NULL,
CONSTRAINT [PK_ApplicationUserTokens] PRIMARY KEY CLUSTERED
(
[UserId] ASC,
[LoginProvider] ASC,
[Name] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE [dbo].[ApplicationRoleClaim] WITH CHECK ADD CONSTRAINT [FK_ApplicationRoleClaims_ApplicationRoles_RoleId] FOREIGN KEY([RoleId])
REFERENCES [dbo].[ApplicationRole] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[ApplicationRoleClaim] CHECK CONSTRAINT [FK_ApplicationRoleClaims_ApplicationRoles_RoleId]
GO
ALTER TABLE [dbo].[ApplicationUser] WITH CHECK ADD CONSTRAINT [FK_ApplicationUsers_Club] FOREIGN KEY([ClubId])
REFERENCES [dbo].[Club] ([Id])
GO
ALTER TABLE [dbo].[ApplicationUser] CHECK CONSTRAINT [FK_ApplicationUsers_Club]
GO
ALTER TABLE [dbo].[ApplicationUserClaim] WITH CHECK ADD CONSTRAINT [FK_ApplicationUserClaims_ApplicationUsers_UserId] FOREIGN KEY([UserId])
REFERENCES [dbo].[ApplicationUser] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[ApplicationUserClaim] CHECK CONSTRAINT [FK_ApplicationUserClaims_ApplicationUsers_UserId]
GO
ALTER TABLE [dbo].[ApplicationUserLogin] WITH CHECK ADD CONSTRAINT [FK_ApplicationUserLogins_ApplicationUsers_UserId] FOREIGN KEY([UserId])
REFERENCES [dbo].[ApplicationUser] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[ApplicationUserLogin] CHECK CONSTRAINT [FK_ApplicationUserLogins_ApplicationUsers_UserId]
GO
ALTER TABLE [dbo].[ApplicationUserRole] WITH CHECK ADD CONSTRAINT [FK_ApplicationUserRole_ApplicationRole] FOREIGN KEY([RoleId])
REFERENCES [dbo].[ApplicationRole] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[ApplicationUserRole] CHECK CONSTRAINT [FK_ApplicationUserRole_ApplicationRole]
GO
ALTER TABLE [dbo].[ApplicationUserRole] WITH CHECK ADD CONSTRAINT [FK_ApplicationUserRole_ApplicationUser] FOREIGN KEY([UserId])
REFERENCES [dbo].[ApplicationUser] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[ApplicationUserRole] CHECK CONSTRAINT [FK_ApplicationUserRole_ApplicationUser]
GO
ALTER TABLE [dbo].[ApplicationUserToken] WITH CHECK ADD CONSTRAINT [FK_ApplicationUserTokens_ApplicationUsers_UserId] FOREIGN KEY([UserId])
REFERENCES [dbo].[ApplicationUser] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[ApplicationUserToken] CHECK CONSTRAINT [FK_ApplicationUserTokens_ApplicationUsers_UserId]
GO

SQL Performance, Execution plan showing mostly Index Scan instead of Index Seek

I am running below query, which is returning mostly 25 records. But it is taking almost 20 seconds. Also the total number of records in the table is less than 400,000.
SELECT * FROM Tickets
LEFT OUTER JOIN HouseAccounts ON (Tickets.lHouseAccount_ID = HouseAccounts.lAccountID)
LEFT OUTER JOIN Customers ON (Tickets.lCustomerID = Customers.lCustomerID)
LEFT OUTER JOIN Vehicles ON (Tickets.lVehicleID = Vehicles.lVehicleID)
WHERE (Tickets.sTicket_Number) NOT LIKE 'ADJ%' AND dbo.DateOnly(Tickets.dtCreated) between DATEADD(day, -60, dbo.DateOnly(GETDATE()))
and dbo.DateOnly(GETDATE()) AND (Tickets.bDeleted = 0 or Tickets.bDeleted IS NULL)
Below is the Tickets table structure
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Tickets](
[Ticket_ID] [int] IDENTITY(1,1) NOT NULL,
[lLocationID] [int] NULL,
[dtCreated] [datetime] NULL,
[dtUpdated] [datetime] NULL,
[dtIn] [datetime] NULL,
[dtOut] [datetime] NULL,
[sTicket_Number] [nvarchar](10) NULL,
[dblTotal] [float] NULL,
[dblTaxes] [float] NULL,
[dblTendered] [float] NULL,
[dblChangeDue] [float] NULL,
[bPaid] [smallint] NULL,
[bCash] [smallint] NULL,
[bCreditCard] [smallint] NULL,
[bGiftCard] [smallint] NULL,
[bHouseAccount] [smallint] NULL,
[lHouseAccount_ID] [int] NULL,
[sUserName] [nvarchar](25) NULL,
[lUserID] [int] NULL,
[lShiftNumber] [int] NULL,
[imgSignature] [image] NULL,
[sSignatureFileName] [nvarchar](25) NULL,
[sPlate] [nvarchar](10) NULL,
[sMake] [nvarchar](20) NULL,
[sCarNumber] [nvarchar](25) NULL,
[sDriverName] [nvarchar](64) NULL,
[sZipcode] [nvarchar](5) NULL,
[sAge] [nvarchar](10) NULL,
[sGender] [nvarchar](10) NULL,
[sFleetCard] [nvarchar](25) NULL,
[sFleetCardExp] [nvarchar](8) NULL,
[bCheck] [smallint] NULL,
[lVIPAccountID] [int] NULL,
[lPointsThisVisit] [float] NULL,
[lGreeterID] [int] NULL,
[lCustomerID] [int] NULL,
[lVehicleID] [int] NULL,
[lWorkOrderID] [int] NULL,
[sWorkOrderNumber] [nvarchar](8) NULL,
[sVehicleMake] [nvarchar](20) NULL,
[sVehicleColor] [nvarchar](20) NULL,
[sVehicleState] [nvarchar](2) NULL,
[sVehiclePlate] [nvarchar](9) NULL,
[sVehicleDamage] [nvarchar](100) NULL,
[sCustomerName] [nvarchar](25) NULL,
[dtReturnDate] [datetime] NULL,
[lOdometer] [int] NULL,
[sRoomNumber] [nvarchar](6) NULL,
[sSpaceNumber] [nvarchar](50) NULL,
[bExpressTicket] [smallint] NULL,
[lRateStructureId] [int] NULL,
[sRateStructure] [nvarchar](25) NULL,
[mRate] [money] NULL,
[mSurcharge] [money] NULL,
[mValidation] [money] NULL,
[mPrepaid] [money] NULL,
[mRefund] [money] NULL,
[mMisc] [money] NULL,
[bVoided] [smallint] NULL,
[bCheckedOut] [smallint] NULL,
[bClosedOut] [smallint] NULL,
[bRefunded] [smallint] NULL,
[lParkerId] [int] NULL,
[bUpdated] [smallint] NULL,
[bIndoor] [smallint] NULL,
[iTimesPrinted] [smallint] NULL,
[bAudit] [bit] NULL,
[bArchived] [bit] NULL,
[lCounterId] [int] NULL,
[bPaymentOther] [bit] NULL,
[sPaymentDescription] [nvarchar](50) NULL,
[bScanned] [bit] NULL,
[bPrinted] [bit] NULL,
[bReversed] [bit] NULL,
[sCashierTerminal] [nvarchar](50) NULL,
[sGreeterTerminal] [nvarchar](50) NULL,
[bLocked] [bit] NULL,
[bWash] [bit] NULL,
[bDeleted] [bit] NULL,
[sDeletedBy] [nvarchar](125) NULL,
[dtClosed] [datetime] NULL,
[lCloserId] [int] NULL,
[lCloserId2] [int] NULL,
[bBarcodeScanned] [bit] NULL,
CONSTRAINT [aaaaaTickets_PK] PRIMARY KEY NONCLUSTERED
(
[Ticket_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON, FILLFACTOR = 65) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
ALTER TABLE [dbo].[Tickets] ADD CONSTRAINT [DF__Tickets__dblTota__014935CB] DEFAULT ((0)) FOR [dblTotal]
GO
ALTER TABLE [dbo].[Tickets] ADD CONSTRAINT [DF__Tickets__bPaid__023D5A04] DEFAULT ((0)) FOR [bPaid]
GO
ALTER TABLE [dbo].[Tickets] ADD CONSTRAINT [DF__Tickets__bCash__03317E3D] DEFAULT ((0)) FOR [bCash]
GO
ALTER TABLE [dbo].[Tickets] ADD CONSTRAINT [DF__Tickets__bCredit__0425A276] DEFAULT ((0)) FOR [bCreditCard]
GO
ALTER TABLE [dbo].[Tickets] ADD CONSTRAINT [DF__Tickets__bGiftCa__0519C6AF] DEFAULT ((0)) FOR [bGiftCard]
GO
And, here is the index and execution plan-
I have already tried with Update Statistics and updating indexes. However, nothing helped. Please suggest, how can I improve the performance of the query.
Execution Plan.sqlplan
Execution Plan.xml
Indexes.xlsx
You should avoid scalar and multistatement UDFs if possible, because they are slow. And You should definitely avoid them in conditions, because they are not sargable. Replacing dbo.DateOnly( with Convert(date, should help.
The thing I am curious about - are there tickets from the future? And if there are, You really want to skip them? Chances are, You can replace that between with simple Tickets.dtCreated >= convert(date, DATEADD(day, -60, GETDATE())).

refreshing generated code from dbml

I've added two new tables to the database.
I've dropped them on the design surface.
My understanding is that it should just automatically generate the design.cs code as a result.
It did, according to my faulty memory, when I added a new table last week, but not this week.
I checked the references in csproj and everything looks OK there.
I tried the RunCustomTool, but that didn't seem to pull anything in to either the DBML or the designer.cs.
No combination of deleting, saving, and re-adding has had any effect.
This is using the MSLinqToSQLGenerator, not SQLMetal
It feels like there is some simple trick I'm missing.
UPDATE: So the problem is with a specific table.
If I add this table, it generates correctly.
CREATE TABLE [dbo].[_LeakageClass](
[id] [int] NOT NULL,
[Class] [nvarchar](25) NOT NULL,
[Description] [nvarchar](50) NOT NULL
CONSTRAINT [PK__LeakageClass] 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]
If I add this table, it quits working and nothing else generates code from then on.
CREATE TABLE [dbo].[_SeatSize](
[model] [int] NOT NULL,
[ValveSize] [int] NOT NULL,
[SeatSize] [int] NOT NULL,
[Stroke] [int] NOT NULL
CONSTRAINT [PK__SeatSize] PRIMARY KEY CLUSTERED
(
[model] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
It couldn't handle having a field named similar to the table.
CREATE TABLE [dbo].[_SeatSize](
[SeatSize] [int] NOT NULL,
doesn't work.
CREATE TABLE [dbo].[_SeatSize](
[SeatSizer] [int] NOT NULL,
works fine. Note that the underscore prefix on the table isn't enough to make a difference.

codeigniter join problem

Hello all i have a problem that when i try to join my comment table it show nothing
here is my code
$this->db->select('*,users.profil_billed as profil_billed, forum_traad.id as traad_id');
$this->db->from('forum_traad');
$this->db->join('users', 'forum_traad.brugernavn = users.username');
$this->db->where('forum_traad.fk_forum_kategori', $id);
$this->db->join('forum_kommentare', 'forum_traad.id = forum_kommentare.fk_forum_traad');
$this->db->where('forum_kommentare.fk_forum_traad', 'forum_traad.id');
$this->db->order_by("forum_traad.id", "DESC");
its then i put this in it show nothing, and i dont know why.. do i need some left join, right join etc.? i have try all of it :d
$this->db->join('forum_kommentare', 'forum_traad.id = forum_kommentare.fk_forum_traad');
$this->db->where('forum_kommentare.fk_forum_traad', 'forum_traad.id');
kommentare = comments
traad = thread
brugernavn = username
kategori = categori
its danish,
sorry my bad english hope some one can help me out
my database structure is this and im using mysql
CREATE TABLE `forum_kategori` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`kategori` text NOT NULL,
`beskrivelse` mediumtext NOT NULL,
`godkendt` varchar(4) NOT NULL DEFAULT 'ja',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=10;
CREATE TABLE `forum_kommentare` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`fk_forum_traad` int(11) NOT NULL,
`brugernavn` text NOT NULL,
`indhold` mediumtext NOT NULL,
`dato` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`time` text NOT NULL,
`godkendt` varchar(4) NOT NULL DEFAULT 'ja',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=28;
CREATE TABLE `forum_traad` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`overskrift` text NOT NULL,
`indhold` mediumtext NOT NULL,
`fk_forum_kategori` int(11) NOT NULL,
`brugernavn` text NOT NULL,
`dato` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`godkendt` varchar(4) NOT NULL DEFAULT 'ja',
`time` text NOT NULL,
`status` varchar(8) NOT NULL DEFAULT 'aaben',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=4;
CREATE TABLE `users` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(80) NOT NULL,
`password` text NOT NULL,
`kon` varchar(5) NOT NULL,
`alder` text NOT NULL,
`hood` varchar(4) DEFAULT NULL,
`fornavn` varchar(60) DEFAULT NULL,
`efternavn` varchar(100) DEFAULT NULL,
`city` text,
`ip` varchar(20) DEFAULT NULL,
`level` text,
`email` text,
`point` int(11) NOT NULL,
`oprettet` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`fritekst` mediumtext NOT NULL,
`profil_billed` text NOT NULL,
`online` varchar(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=31;
and it return nothing and no errors it only show a message i have done with a else statement that said "there is no threads on this categori", i have try with left join, right join inner join full join, ye all of it :S
You should try using a left join on your joins and work from there. If that doesn't work then there isn't a link between the tables.
Try this code:
$this->db->select('*,users.profil_billed as profil_billed, forum_traad.id as traad_id');
$this->db->from('forum_traad');
$this->db->join('users', 'forum_traad.brugernavn = users.username');
$this->db->join('forum_kommentare', 'forum_traad.id = forum_kommentare.fk_forum_traad');
$this->db->where('forum_traad.fk_forum_kategori', $id);
$this->db->order_by("forum_traad.id", "DESC");
You can use after $this->db->get() the
print $this->db->last_query();
and check what's wrong.

How to select Values from several tables

my three table structure are :
USE [DB_OrderV2]
GO
/****** Object: Table [dbo].[tblPageInfo] Script Date: 07/24/2010 23:16:18 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tblPageInfo](
[Code] [int] IDENTITY(1,1) NOT NULL,
[PageID] [smallint] NOT NULL,
[PageName] [nvarchar](80) NOT NULL,
[Description] [nvarchar](80) NOT NULL,
[Status] [tinyint] NOT NULL,
[CreateUserID] [smallint] NULL,
[CreateDate] [smalldatetime] NULL,
[UpdateUserID] [smallint] NULL,
[UpdateDate] [smalldatetime] NULL,
CONSTRAINT [PK_tblPageInfo] PRIMARY KEY CLUSTERED
(
[PageID] 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
USE [DB_OrderV2]
GO
/****** Object: Table [dbo].[tblUserType] Script Date: 07/24/2010 23:17:42 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tblUserType](
[Code] [int] IDENTITY(1,1) NOT NULL,
[UserTypeID] [smallint] NOT NULL,
[UserType] [nvarchar](50) NOT NULL,
[Status] [tinyint] NULL,
[CreateUserID] [smallint] NULL,
[CreateDate] [smalldatetime] NULL,
[UpdateUserID] [smallint] NULL,
[UpdateDate] [smalldatetime] NULL,
CONSTRAINT [PK_tblUserType] PRIMARY KEY CLUSTERED
(
[UserTypeID] 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
USE [DB_OrderV2]
GO
/****** Object: Table [dbo].[tblUserInfo] Script Date: 07/24/2010 23:18:33 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[tblUserInfo](
[Code] [int] IDENTITY(1,1) NOT NULL,
[UserID] [smallint] NOT NULL,
[UserName] [nvarchar](50) NOT NULL,
[LoginName] [nvarchar](50) NOT NULL,
[Password] [nvarchar](50) NOT NULL,
[UserTypeID] [smallint] NOT NULL,
[Status] [tinyint] NOT NULL,
[ActiveDate] [datetime] NULL,
[CreateUserID] [smallint] NULL,
[CreateDate] [smalldatetime] NULL,
[UpdateUserID] [smallint] NULL,
[UpdateDate] [smalldatetime] NULL,
CONSTRAINT [PK_tblUserInfo_1] 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]
) ON [PRIMARY]
GO
Using the above table i need a select query to select several fields .but how ?
query = this.Context.tblUserInfos
.Where(p => p.Status == 1)
.Select(p => new { p.tblUserType.UserTypeID,p.tblUserType.UserType,});
return query;
above LINQ query works well ,but here i need to select UserRoleID from tblUserRole table , and PageName from tblPageInfo table .What to write on above query to select those fields.
Just like in SQL you will want to use a join. So something like
query = from p in Context.tblUserInfos
join u in Context.tblUserRole Where p.UserRoleID equals u.UserRoleID
join n in context.tblPageInfo where p.PageName equals n.PageName
where p.Status == 1
select new {p.tblUserType.UserTypeId, p.tblUserType.UserType, u.UserRoleId, n.PageName};
I wasn't quite able to parse what you were trying to join on from each table, but that should get you started.
Edit
I think I may have gotten my syntax confused.
Straight up Labmda Version
query = Context.tblUserInfos
.Join(Context.tblUserRole, info => info.UserRoleID, user => user.UserRoleID, (info, user) => new {Info = info, User = user})
.Join(Context.tblPageInfo, info2 => info2.PageName, name => name.PageName, (info2, name) => new {Info2 = info2, Name = name})
.Where(p => p.Status == 1)
.Select(p => new { p.tblUserType.UserTypeID,p.tblUserType.UserType, User, Name});
I haven't tested that, but I think that's correct.

Resources