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()'
Related
I'm using EF Core 2.2.6 and the schema generated on my local SQL Server 2017 (v14.0) is different from the schema generated on Azure (SQL Server v12.0)
My entity looks like this:
public class MyEntity
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Description { get; set; }
}
My DbContext is:
protected override void OnModelCreating(ModelBuilder modelBuilder) {
modelBuilder.Entity<MyEntity>().ToTable("MyTable").HasKey(m => m.Id);
modelBuilder.Entity<MyEntity>().Property(m => m.Name).IsRequired();
}
But the problem is that in the Azure SQL database, the ALLOW_ROW_LOCKS is missing. Why is the generated schema different? Is there a way to force EF to add the ALLOW_ROW_LOCKS = ON (and ALLOW_PAGE_LOCKS = ON)?
CREATE TABLE MyEntity
(
[Id] [UNIQUEIDENTIFIER] NOT NULL,
[Name] [NVARCHAR](MAX) NOT NULL,
[Description] [NVARCHAR](MAX) NULL,
CONSTRAINT [PK_MyEntity]
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]
GO
This is how it looks in Azure:
CREATE TABLE MyEntity
(
[Id] [UNIQUEIDENTIFIER] NOT NULL,
[Name] [NVARCHAR](MAX) NOT NULL,
[Description] [NVARCHAR](MAX) NULL,
CONSTRAINT [PK_MyEntity]
PRIMARY KEY CLUSTERED ([Id] ASC)
WITH (STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
GO
Actually, if you don't set the ALLOW_ROW_LOCKS = OFF or ALLOW_PAGE_LOCKS = OFF, the table schema will be the same.
No matter in SQL Server or Azure SQL database, both the default value of ALLOW_ROW_LOCKS and ALLOW_PAGE_LOCKS are ON:
Reference: CREATE TABLE (Transact-SQL) :
You said you have the performance problems on Azure SQL database, I agree with Jeroen Mostert that it's not impossible that changing these flags is the solution.
Maybe this document Monitoring and performance tuning can give you more guides to solve the Azure SQL database performance problem.
Hope this helps.
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
I am trying to create custom tables for Identity Authentication, but I keep getting this error no matter how many times I have tried to recreate the Identity tables:
The entity types 'BBRoleType' and 'UserRoleType' cannot share table 'UserRoleTypes' because they are not in the same type hierarchy or do not have a valid one to one foreign key relationship with matching primary keys between them.
This is my User tables in the database:
And exported as SQL:
/****** Object: Table [dbo].[User] Script Date: 21/12/2015 18:42:21 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[User](
[Id] [uniqueidentifier] NOT NULL,
[Email] [nvarchar](255) NOT NULL,
[IsConfirmed] [bit] NOT NULL,
[PasswordHash] [nvarchar](500) NULL,
[SecurityStamp] [nvarchar](255) NULL,
[UserName] [nvarchar](255) NOT NULL,
[CreateDate] [datetime] NOT NULL,
[LastOnlineDate] [datetime] NOT NULL,
[BirthDate] [datetime] NULL,
[FacebookAccessToken] [nvarchar](max) NOT NULL,
[FacebookName] [nvarchar](500) NOT NULL,
[FacebookId] [nvarchar](max) NOT NULL,
CONSTRAINT [PK_User] 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]
GO
/****** Object: Table [dbo].[UserClaim] Script Date: 21/12/2015 18:42:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[UserClaim](
[Id] [bigint] NOT NULL,
[UserId] [uniqueidentifier] NOT NULL,
[ClaimValue] [nvarchar](max) NOT NULL,
[ClaimType] [nvarchar](max) NOT NULL,
CONSTRAINT [PK_UserClaim] 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]
GO
/****** Object: Table [dbo].[UserLogin] Script Date: 21/12/2015 18:42:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[UserLogin](
[UserId] [uniqueidentifier] NOT NULL,
[ProviderKey] [nvarchar](max) NOT NULL,
[LoginProvider] [nvarchar](max) NOT NULL,
[UserLoginId] [uniqueidentifier] NOT NULL,
CONSTRAINT [PK_UserLogin] PRIMARY KEY CLUSTERED
(
[UserLoginId] 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]
GO
/****** Object: Table [dbo].[UserRole] Script Date: 21/12/2015 18:42:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[UserRole](
[RoleId] [uniqueidentifier] NOT NULL,
[UserId] [uniqueidentifier] NOT NULL
) ON [PRIMARY]
GO
/****** Object: Table [dbo].[UserRoleType] Script Date: 21/12/2015 18:42:22 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[UserRoleType](
[Id] [uniqueidentifier] NOT NULL,
[Name] [nvarchar](255) NOT NULL,
CONSTRAINT [PK_UserRoleType] 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
ALTER TABLE [dbo].[User] ADD CONSTRAINT [DF_User_IsConfirmed] DEFAULT ((0)) FOR [IsConfirmed]
GO
ALTER TABLE [dbo].[UserLogin] ADD CONSTRAINT [DF_UserLogin_UserLoginId] DEFAULT (newid()) FOR [UserLoginId]
GO
ALTER TABLE [dbo].[UserRoleType] ADD CONSTRAINT [DF_UserRoleType_Id] DEFAULT (newid()) FOR [Id]
GO
ALTER TABLE [dbo].[UserClaim] WITH CHECK ADD CONSTRAINT [FK_UserClaim_User] FOREIGN KEY([UserId])
REFERENCES [dbo].[User] ([Id])
GO
ALTER TABLE [dbo].[UserClaim] CHECK CONSTRAINT [FK_UserClaim_User]
GO
ALTER TABLE [dbo].[UserLogin] WITH CHECK ADD CONSTRAINT [FK_UserLogin_User] FOREIGN KEY([UserId])
REFERENCES [dbo].[User] ([Id])
GO
ALTER TABLE [dbo].[UserLogin] CHECK CONSTRAINT [FK_UserLogin_User]
GO
ALTER TABLE [dbo].[UserRole] WITH CHECK ADD CONSTRAINT [FK_UserRole_User] FOREIGN KEY([UserId])
REFERENCES [dbo].[User] ([Id])
GO
ALTER TABLE [dbo].[UserRole] CHECK CONSTRAINT [FK_UserRole_User]
GO
ALTER TABLE [dbo].[UserRole] WITH CHECK ADD CONSTRAINT [FK_UserRole_UserRoleTyp] FOREIGN KEY([RoleId])
REFERENCES [dbo].[UserRoleType] ([Id])
GO
ALTER TABLE [dbo].[UserRole] CHECK CONSTRAINT [FK_UserRole_UserRoleTyp]
GO
After creating the table, I have added a ADO.NET Data Entity Model for the database.
I have created these classes to map to the custom Identity classes:
public class BBUserLogin : IdentityUserLogin<Guid> { }
public class BBUserRole : IdentityUserRole<Guid> { }
public class BBRoleType : IdentityRole<Guid,BBUserRole> { }
public class BBUserClaim : IdentityUserClaim<Guid> { }
public class BBUser : IdentityUser<Guid, BBUserLogin, BBUserRole, BBUserClaim>
{
public DateTime CreateDate { get; set; }
public DateTime LastOnlineDate { get; set; }
public DateTime? BirthDate { get; set; }
public string FacebookAccessToken { get; set; }
public string FacebookName { get; set; }
public string FacebookId { get; set; }
public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<BBUser, Guid> manager)
{
var userIdentity = await manager.CreateIdentityAsync(this, DefaultAuthenticationTypes.ApplicationCookie);
userIdentity.AddClaim(new Claim(TCCustomClaimTypes.FirstName, this.FacebookName.SubstringUpToFirst(' ')));
return userIdentity;
}
}
And then setup my DbContext as this:
public class ApplicationDbContext : IdentityDbContext<BBUser, BBRoleType, Guid, BBUserLogin, BBUserRole, BBUserClaim>
{
public ApplicationDbContext() : base("MyIdentityConnection")
{
}
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
base.OnModelCreating(modelBuilder);
modelBuilder.HasDefaultSchema("dbo");
modelBuilder.Entity<BBUser>().ToTable("User");
modelBuilder.Entity<BBUserClaim>().ToTable("UserClaim");
modelBuilder.Entity<BBUserLogin>().ToTable("UserLogin");
modelBuilder.Entity<BBUserRole>().ToTable("UserRole");
modelBuilder.Entity<BBRoleType>().ToTable("UserRoleType");
modelBuilder.Entity<BBUser>().Property(x => x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
modelBuilder.Entity<BBUserClaim>().Property(x => x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
modelBuilder.Entity<BBRoleType>().Property(x => x.Id).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
}
Not that I think i matters, but I am using Guid/[uniqueidentifier] as Ids where I can (the places where the generic TKey is used). The IdentityUserClaim does not allow to change the Id-type, so I am using a bigint for that. Not that I think it matters :-)
I have been banging my head against the wall the entire day with this problem, but I can't figure out what I have done wrong.
It looks to me that the key names Id, Id, UserId, and RoleId need to have proper naming. Can you change the key 'Id' to 'UserId' on the 'User' table? Drop the Id key on UserClaim table. Change 'Id' on UserRoleType table to RoleId.
I think that will fix your issue.
I am a new ASP.NET developer and I have 2 inputs in a form as DateTimes; StartDate and EndDate. I want to make sure that both of them are within the StartDate and EndDate of the Parent from another table. The logic should be as following:
Check if the StartDate of the items comes before the EndDate.
Check if the StartDate & EndDate of the inserted item is within the range of the StartDate and EndDate in the Customers table
So how can I do this logic?
For your information, I have two tables in the database, namely; Customers and Items.Their schema are:
Customers Table:
CREATE TABLE [dbo].[Customers](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NULL,
[Job] [varchar](50) NULL,
[StartDate] [datetime] NOT NULL,
[EndDate] [datetime] NOT NULL,
CONSTRAINT [PK_Customers] 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]
Items Table:
CREATE TABLE [dbo].[Items](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Name] [varchar](50) NOT NULL,
[Description] [varchar](50) NULL,
[StartDate] [datetime] NOT NULL,
[EndDate] [datetime] NOT NULL,
[CustomerID] [int] NOT NULL,
CONSTRAINT [PK_Items] 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
SET ANSI_PADDING OFF
GO
ALTER TABLE [dbo].[Items] WITH CHECK ADD CONSTRAINT [FK_Items_Customers] FOREIGN KEY([CustomerID])
REFERENCES [dbo].[Customers] ([ID])
GO
ALTER TABLE [dbo].[Items] CHECK CONSTRAINT [FK_Items_Customers]
GO
My C# Code:
protected void btnSubmit_Click(object sender, EventArgs e)
{
DateTime startDate = Convert.ToDateTime(txtStartDate.Text);
DateTime endDate = Convert.ToDateTime(txtEndDate.Text);
if (DateTime.Compare(startDate, endDate) <= 0)
{
using (TestDBEntities1 TEntities = new TestDBEntities1())
{
var newItem = new Item
{
Name = txtName.Text,
Description = txtDesc.Text,
StartDate = startDate,
EndDate = endDate,
CustomerID = Convert.ToInt32(ComboBox1.SelectedValue)
};
TEntities.Items.AddObject(newItem);
TEntities.SaveChanges();
}
lblMessage.Text = "Successfully Added :)";
}
else
{
lblMessage.Text = "Error!!!";
}
}
NOTE: I am using LINQ for querying the database. I am only missing the part of doing the logic for checking if the StartDate & EndDate of the inserted item is within the Dates in the Customers table.
Explanation:
For example, let us assume we have StartDate#1 and EndDate#1 for an item that will be inserted. In the Customers table, I have StartDate#2 and EndDate#2. The logic should do the following:
check if the StartDate#1 comes before EndDate#1
Then, check if StartDate#1 and EndDate#1 are falling within the range of StartDate#2 and EndDate#2
I have a single entity that always duplicate a row when it needs to update:
protected static Task RegisterToDisc(Task task)
{
try
{
using (DataContext context = new DataContext())
{
//this will print an actual existing id from the db
_log.Debug(task.ID);
context.Tasks.InsertOnSubmit(task);
context.SubmitChanges();
}
}
catch(Exception e)
{
//...
}
return task;
}
When I print the id before the save, it is actually prints out an id that is really exists in the db.
this is the table:
CREATE TABLE [dbo].[TaskSet](
[ID] [int] IDENTITY(1,1) NOT NULL,
[Message] [nvarchar](max) NOT NULL,
[Result] [nvarchar](max) NOT NULL,
[Status] [int] NOT NULL,
[Priority] [int] NOT NULL,
[Name] [nvarchar](max) NOT NULL,
[DateTimeAsked] [datetime] NOT NULL,
[DateTimePerfomed] [datetime] NOT NULL,
[SessionID] [nvarchar](max) NOT NULL,
CONSTRAINT [PK_TaskSet] 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
Edit
The task is comming from the database already, task.ID contains a number that is exists in the database, how come Linq inserts an entity with PK that is not null and in the db already.
in java hibernate you neet to context.insertOrUpdate(task); and it will decide what to do by the primary key.
InsertOnSubmit always marks the object for insertion. if you want to update the object u need to read it from database like
var objToUpdate = context.Tasks.SingleOrDefault(x=>x.Id == Id);
objToUpdate.Property1 = "updated value";
objToUpdate.Property2 = "updated value";
//do it for all properties that need updating
context.SubmitChanges();//since the object is tracked by context it will automatically generate sql to reflect update in db