Some of the string properties in the class do not have a [Required] attribute, and when migrating it to SQL Server, it adds a NOT NULL property. I have revised the code so much but didn't reach any solution yet.
public class Stores
{
[Key]
public int StoreID { get; set; }
[Required]
[Display(Name = "Store Name")]
public string StoreName { get; set; } = string.Empty;
[Display(Name = "Store Bio")]
public string Bio { get; set; } = string.Empty;
[Display(Name = "Store Description")]
public string Description { get; set; } = string.Empty;
}
This is the SQL code generated
CREATE TABLE [dbo].[Stores]
(
[StoreID] INT IDENTITY (1, 1) NOT NULL,
[StoreName] NVARCHAR (MAX) NOT NULL,
[Bio] NVARCHAR (MAX) NOT NULL,
[Description] NVARCHAR (MAX) NOT NULL,
[BrandsBrandID] INT NULL,
[CategoriesCategoryID] INT NULL,
[CollectionsCollectionID] INT NULL,
[ProductsProductID] INT NULL,
CONSTRAINT [PK_Stores]
PRIMARY KEY CLUSTERED ([StoreID] ASC),
CONSTRAINT [FK_Stores_Brands_BrandsBrandID]
FOREIGN KEY ([BrandsBrandID]) REFERENCES [dbo].[Brands] ([BrandID]),
CONSTRAINT [FK_Stores_Categories_CategoriesCategoryID]
FOREIGN KEY ([CategoriesCategoryID]) REFERENCES [dbo].[Categories] ([CategoryID]),
CONSTRAINT [FK_Stores_Collections_CollectionsCollectionID]
FOREIGN KEY ([CollectionsCollectionID]) REFERENCES [dbo].[Collections] ([CollectionID]),
CONSTRAINT [FK_Stores_Products_ProductsProductID]
FOREIGN KEY ([ProductsProductID]) REFERENCES [dbo].[Products] ([ProductID])
);
This is the sql code generated Image
Your Code seems totally correct. So try this one: Clear SQL cache.
Select Edit > IntelliSense > Refresh Local Cache
or
Press Ctrl+Shift+R
Related
I have two tables, one for primary key and second for foreign key. When I write the code to insert the data, I get an error.
ALTER PROCEDURE [dbo].[ImageHotSpotCRUD]
#ImaheHSMId int = NULL,
#ImaheHSName varchar(MAX) = '' ,
-- #patImage [varbinary](max)= NULL
#ImaheHSPath varchar(MAX) = '' ,
#ImaheHSDId int = NULL,
#ImaheHSDFKId int = NULL,
#ImaheHSXCordinate varchar(50) = '',
#ImaheHSYCordinate varchar(50) = '' ,
#ImaheHSDisc varchar(MAX) = '' ,
#IsActive varchar(1) = '' ,
#Created_by varchar(20) = '' ,
#CreatedDate datetime ='',
#ModifyDate datetime ='',
#ModifyBy varchar(50) = '',
#Mode varchar(1) =''
AS
BEGIN
SET NOCOUNT ON;
IF #Mode = '1'
BEGIN
-- Primary key table entry
DECLARE #ImageNEWPKId int = NULL
SELECT #ImageNEWPKId = HotSpotID
FROM M_ImageHotSpot
WHERE ImageName = #ImaheHSName
IF (#ImageNEWPKId IS NULL)
BEGIN
INSERT INTO M_ImageHotSpot (ImageName, ImagePath, Created_by, Created_date)
VALUES (#ImaheHSName, #ImaheHSPath, #Created_by, GETDATE())
SELECT #ImageNEWPKId = SCOPE_IDENTITY()
END
-- Foreign key table entry
DECLARE #ImageNEWDetailPKId int = NULL
SELECT #ImageNEWDetailPKId = HPDetailID
FROM M_ImageHotSpotDetail
WHERE HotSpotDescription = #ImaheHSDisc
IF (#ImageNEWDetailPKId IS NULL)
BEGIN
INSERT INTO M_ImageHotSpotDetail (HotspotIDFK, XCordinate, YCordinate, HotSpotDescription, CreatedByID, CreatedDate)
VALUES (#ImageNEWPKId, #ImaheHSXCordinate, #ImaheHSYCordinate, #ImaheHSDisc, #Created_by, GETDATE())
-- SELECT #ImaheHSMId = SCOPE_IDENTITY()
END
END
END
Here how I pass the data during button click in aspx.cs page:
exec ImageHotSpotCRUD
#Mode = '1', #ImaheHSName = 'x.jpeg', #ImaheHSPath = 'c:\',
#Created_by = 'ADMIN', #ImaheHSXCordinate = '100', #ImaheHSYCordinate = '100',
#ImaheHSDisc = 'You Selected Computer'
GO
I am using SQL Server Management Studio 18.
EDIT CODE 1
public int ImaheHSMId { get; set; }
public string ImaheHSName { get; set; }
public string ImaheHSPath { get; set; }
//Foreign Key Field
public int ImaheHSDId { get; set; }
//Foreign Key Id store here
public int ImaheHSDFKId { get; set; }
public string ImaheHSXCordinate { get; set; }
public string ImaheHSYCordinate { get; set; }
public string ImaheHSDisc { get; set; }
public string UserId { get; set; }
public bool IsDeleted { get; set; }
public bool IsActive { get; set; }
This are my class property and here is my Table Information. I did every thing perfect but still no data inserted.
Edit Code 2
Here is My both the table script.
CREATE TABLE [TRIEU].[M_ImageHotSpot](
[HotSpotID] [int] IDENTITY(1,1) NOT NULL,
[ImageName] [nvarchar](max) NULL,
[ImagePath] [nvarchar](max) NULL,
[IsActive] [bit] NULL,
[IsDeleted] [bit] NULL,
[Created_by] [nvarchar](18) NULL,
[Created_date] [datetime] NULL,
[Modified_by] [nvarchar](18) NULL,
[Modified_date] [datetime] NULL,
[stats_flag] [char](1) NULL,
CONSTRAINT [PK_M_ImageHotSpot] PRIMARY KEY CLUSTERED
(
[HotSpotID] 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
CREATE TABLE [TRIEU].[M_ImageHotSpotDetail](
[HPDetailID] [int] IDENTITY(1,1) NOT NULL,
[HotspotIDFK] [int] NULL,
[XCordinate] [nvarchar](50) NULL,
[YCordinate] [nvarchar](50) NULL,
[HotSpotDescription] [nvarchar](max) NULL,
[IsActive] [bit] NULL,
[IsDeleted] [bit] NULL,
[Created_by] [nvarchar](18) NULL,
[Created_date] [datetime] NULL,
[Modified_by] [nvarchar](18) NULL,
[Modified_date] [datetime] NULL,
[stats_flag] [char](1) NULL,
CONSTRAINT [PK_M_ImageHotSpotDetail] PRIMARY KEY CLUSTERED
(
[HPDetailID] 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
Dear JParmar,
INSERT INTO M_ImageHotSpotDetail (HotspotIDFK, XCordinate, YCordinate, HotSpotDescription, CreatedByID, CreatedDate)
VALUES (#ImageNEWPKId, #ImaheHSXCordinate, #ImaheHSYCordinate, #ImaheHSDisc, #Created_by, GETDATE())
For the above line, CreatedByID and CreatedDate column is not exist in M_ImageHotSpotDetail Table.
I am using spring boot and hibernate for a simple web app. When I am trying to run it I get this error 3 times.
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL via JDBC Statement
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67) ~[hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlString(AbstractSchemaMigrator.java:559) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlStrings(AbstractSchemaMigrator.java:504) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applyForeignKeys(AbstractSchemaMigrator.java:433) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.performMigration(AbstractSchemaMigrator.java:249) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.doMigration(AbstractSchemaMigrator.java:114) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:183) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:72) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:312) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:460) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:892) [hibernate-core-5.2.16.Final.jar:5.2.16.Final]
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:57) [spring-orm-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) [spring-orm-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:390) [spring-orm-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:377) [spring-orm-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) [spring-orm-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1761) [spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1698) [spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:579) [spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:501) [spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:317) [spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228) ~[spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:315) [spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) [spring-beans-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1089) ~[spring-context-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:859) ~[spring-context-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.0.5.RELEASE.jar:5.0.5.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:140) ~[spring-boot-2.0.1.RELEASE.jar:2.0.1.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:759) ~[spring-boot-2.0.1.RELEASE.jar:2.0.1.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:395) ~[spring-boot-2.0.1.RELEASE.jar:2.0.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:327) ~[spring-boot-2.0.1.RELEASE.jar:2.0.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1255) ~[spring-boot-2.0.1.RELEASE.jar:2.0.1.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1243) ~[spring-boot-2.0.1.RELEASE.jar:2.0.1.RELEASE]
at com.reminder.EJA.EjaApplication.main(EjaApplication.java:10) ~[classes/:na]
Caused by: java.sql.SQLException: Cannot add foreign key constraint
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1055) ~[mysql-connector-java-5.1.6.jar:na]
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:956) ~[mysql-connector-java-5.1.6.jar:na]
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3491) ~[mysql-connector-java-5.1.6.jar:na]
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3423) ~[mysql-connector-java-5.1.6.jar:na]
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1936) ~[mysql-connector-java-5.1.6.jar:na]
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2060) ~[mysql-connector-java-5.1.6.jar:na]
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2536) ~[mysql-connector-java-5.1.6.jar:na]
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2465) ~[mysql-connector-java-5.1.6.jar:na]
at com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:734) ~[mysql-connector-java-5.1.6.jar:na]
at com.zaxxer.hikari.pool.ProxyStatement.execute(ProxyStatement.java:95) ~[HikariCP-2.7.8.jar:na]
at com.zaxxer.hikari.pool.HikariProxyStatement.execute(HikariProxyStatement.java) ~[HikariCP-2.7.8.jar:na]
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:54) ~[hibernate-core-5.2.16.Final.jar:5.2.16.Final]
... 33 common frames omitted
It says "Cannot add foreign key constraint". I was checking the column names also I was searching here on stackoverflow but somehow I can not find the answer.
This is my application.properties file:
spring.datasource.url=jdbc:mysql://localhost:3306/EJA
spring.datasource.username=root
spring.datasource.password=database
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.hibernate.ddl-auto = update
This is my database schema:
Here is also create script:
SET #OLD_UNIQUE_CHECKS=##UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET #OLD_FOREIGN_KEY_CHECKS=##FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET #OLD_SQL_MODE=##SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
-- -----------------------------------------------------
-- Schema EJA
-- -----------------------------------------------------
-- -----------------------------------------------------
-- Schema EJA
-- -----------------------------------------------------
CREATE SCHEMA IF NOT EXISTS `EJA` DEFAULT CHARACTER SET utf8 ;
USE `EJA` ;
-- -----------------------------------------------------
-- Table `EJA`.`client`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `EJA`.`client` (
`idClient` INT NOT NULL AUTO_INCREMENT,
`nickname` VARCHAR(45) NOT NULL,
`password` VARCHAR(45) NOT NULL,
PRIMARY KEY (`idClient`),
UNIQUE INDEX `Nickname_UNIQUE` (`nickname` ASC))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `EJA`.`priority`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `EJA`.`priority` (
`idPriority` INT NOT NULL AUTO_INCREMENT,
`priority` INT UNSIGNED NOT NULL,
PRIMARY KEY (`idPriority`))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `EJA`.`state`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `EJA`.`state` (
`idState` INT NOT NULL AUTO_INCREMENT,
`state` VARCHAR(45) NOT NULL,
PRIMARY KEY (`idState`),
UNIQUE INDEX `state_UNIQUE` (`state` ASC))
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `EJA`.`event`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `EJA`.`event` (
`idEvent` INT NOT NULL AUTO_INCREMENT,
`name` VARCHAR(45) NOT NULL,
`from` DATE NOT NULL,
`to` DATE NOT NULL,
`description` VARCHAR(250) NULL,
`Client_idClient` INT NOT NULL,
`Priority_idPriority` INT NOT NULL,
`State_idState` INT NOT NULL,
PRIMARY KEY (`idEvent`, `Priority_idPriority`, `State_idState`, `Client_idClient`),
UNIQUE INDEX `name_UNIQUE` (`name` ASC),
INDEX `fk_Event_Client_idx` (`Client_idClient` ASC),
INDEX `fk_Event_Priority1_idx` (`Priority_idPriority` ASC),
INDEX `fk_Event_State1_idx` (`State_idState` ASC),
UNIQUE INDEX `description_UNIQUE` (`description` ASC),
CONSTRAINT `fk_Event_Client`
FOREIGN KEY (`Client_idClient`)
REFERENCES `EJA`.`client` (`idClient`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_Event_Priority1`
FOREIGN KEY (`Priority_idPriority`)
REFERENCES `EJA`.`priority` (`idPriority`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_Event_State1`
FOREIGN KEY (`State_idState`)
REFERENCES `EJA`.`state` (`idState`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
SET SQL_MODE=#OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=#OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=#OLD_UNIQUE_CHECKS;
And these are my entity classes (without setters/getters and imports):
#Entity
#Table(name = "event")
public class Event {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "idEvent")
private Integer id;
#Column(name = "name")
private String name;
#Column(name = "from")
private Date from;
#Column(name = "to")
private Date to;
#Column(name = "description")
private String description;
#ManyToOne
#JoinColumn(name = "Client_idClient")
private Client client;
#ManyToOne
#JoinColumn(name = "State_idState")
private State state;
#ManyToOne
#JoinColumn(name = "Priority_idPriority")
private Priority priority;
}
#Entity
#Table(name = "client")
public class Client {
#Id
#GeneratedValue
#Column(name = "idClient")
private Integer id;
#Column(name = "nickname")
private String nickname;
#Column(name = "password")
private String password;
#OneToMany(mappedBy = "client", cascade = CascadeType.ALL)
private Collection<Event> events;
}
#Entity
#Table(name = "priority")
public class Priority {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "idPriority")
private Integer id;
#Range(min = 0, max = 10)
#Column(name = "priority")
private Integer priority;
#OneToMany(mappedBy = "priority")
private Collection<Event> event;
}
#Entity
#Table(name = "state")
public class State {
#Id
#Column(name = "idState")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Pattern(regexp = "")
#Column(name = "state")
private String state;
#OneToMany(mappedBy = "state")
private Collection<Event> event;
}
Thank you for any help.
The code will better explain what I'm trying to do.
var data = db.Absences//.AsExpandable()
.Where(a => a.Employee.EmployeeCode == "Emp1" || a.Employee.EmployeeCode == "Emp2" || a.Employee.EmployeeCode == "Emp3" || a.Employee.EmployeeCode == "Emp4" )
.Where(a=> a.Employee.Department.DepartmentCode == "HR" ||a.Employee.Department.DepartmentCode == "FIN" ||a.Employee.Department.DepartmentCode == "IT" )
.Where(a=> a.AbsenceId > 0)
.GroupBy(a => new
{
a.Employee.Department.DepartmentName,
a.Employee.Department.DepartmentCode,
a.Employee.IsPermanent
})
.Select(g => new ResultModel
{
Department = g.Key.DepartmentName,
Permanent = g.Key.IsPermanent,
TotalEmployeesInDepartment = g.Select(e => e.EmployeeCode).Distinct().Count(),
TotalAbsenceRecordsInCategory = g.Count(),
TotalLateCount = g.Select(x=> x.AbsenceCode == "Late").Count(),
TotalSickCount = g.Select(x=> x.AbsenceCode == "Sick").Count(),
TotalOnSiteCount = g.Select(x => x.AbsenceCode == "OnSite").Count(),
LatePercent = g.Select(x => x.AbsenceCode == "Late").Count() * 100.0 / g.Count(),
SickPercent = g.Select(x => x.AbsenceCode == "Sick").Count() * 100.0 / g.Count(),
OnSitePercent = g.Select(x => x.AbsenceCode == "OnSite").Count() * 100.0 / g.Count(),
});
I want total number of absences in a department, grouped by permanent vs non-permanent employees.
TotalAbsenceRecordsInCategory = g.Count() this is calculating fine in the generated SQL.
When I'm trying to get count of absences due to individual reasons the query is not working as expected.
TotalLateCount = g.Select(x=> x.AbsenceCode == "Late").Count(), this is not working, all of them are evaluated as
COUNT(1) AS [A1],
COUNT(1) AS [A2],
COUNT(1) AS [A3],
COUNT(1) AS [A4],.. so on
Below are my tables
CREATE TABLE [dbo].[Employees]
(
[DepartmentCode] [nvarchar](10) NOT NULL,
[EmployeeCode] [nvarchar](10) NOT NULL,
[EmployeeName] [nvarchar](20) NOT NULL,
[IsPermanent] [bit] NOT NULL,
CONSTRAINT [PK_Employees]
PRIMARY KEY CLUSTERED ([DepartmentCode] ASC, [EmployeeCode] 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].[Employees]
ADD CONSTRAINT [DF_Employees_IsPermanent] DEFAULT ((0)) FOR [IsPermanent]
GO
ALTER TABLE [dbo].[Employees] WITH CHECK
ADD CONSTRAINT [FK_Employees_Departments]
FOREIGN KEY([DepartmentCode]) REFERENCES [dbo].[Departments] ([DepartmentCode])
GO
ALTER TABLE [dbo].[Employees] CHECK CONSTRAINT [FK_Employees_Departments]
GO
CREATE TABLE [dbo].[Departments]
(
[DepartmentCode] [nvarchar](10) NOT NULL,
[DepartmentName] [nvarchar](20) NOT NULL,
CONSTRAINT [PK_Departments]
PRIMARY KEY CLUSTERED ([DepartmentCode] 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 [dbo].[Absences]
(
[DepartmentCode] [nvarchar](10) NOT NULL,
[EmployeeCode] [nvarchar](10) NOT NULL,
[AbsenceId] [int] NOT NULL,
[AbsenceCode] [nvarchar](10) NOT NULL,
[AbsenceDate] [date] NOT NULL,
CONSTRAINT [PK_Absences_1]
PRIMARY KEY CLUSTERED ([DepartmentCode] ASC, [EmployeeCode] ASC, [AbsenceId] 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].[Absences] WITH CHECK
ADD CONSTRAINT [FK_Absences_Employees]
FOREIGN KEY([DepartmentCode], [EmployeeCode]) REFERENCES [dbo].[Employees] ([DepartmentCode], [EmployeeCode])
GO
ALTER TABLE [dbo].[Absences] CHECK CONSTRAINT [FK_Absences_Employees]
GO
One alternative is to say
TotalLateCount = g.Count(x=> x.AbsenceCode == "Late")
but this creates nested sub queries which I'm trying to avoid.
Any idea how can I get this to work? ResultModel is a simple class
public class ResultModel
{
public string Department { get; set; }
public bool Permanent { get; set; }
public int TotalAbsenceRecordsInCategory { get; set; }
public int TotalEmployeesInDepartment { get; set; }
public int TotalLateCount { get; set; }
public int TotalSickCount { get; set; }
public int TotalOnSiteCount { get; set; }
public double LatePercent { get; set; }
public double SickPercent { get; set; }
public double OnSitePercent { get; set; }
}
I have the following Quote and Share classes:
public class Quote
{
public Quote(string ticker, string name, decimal lastPrice)
{
this.Ticker = ticker;
this.Name = name;
this.LastPrice = lastPrice;
}
public string Ticker { get; private set; }
public string Name { get; private set; }
public decimal LastPrice { get; private set; }
}
public class Share
{
public Share(Quote quote, int quantity)
{
this.Quote = quote;
this.Quantity = quantity;
}
public Quote Quote { get; private set; }
public int Quantity { get; private set; }
}
And these tables:
CREATE TABLE [dbo].[quotes](
[ticker] [char](5) NOT NULL,
[name] [varchar](60) NOT NULL,
[last_price] [money] NOT NULL,
[bid_price] [money] NULL,
[bid_quantity] [int] NULL,
[ask_price] [money] NULL,
[ask_quantity] [int] NULL,
[high] [money] NULL,
[low] [money] NULL,
[previous_close] [money] NULL,
[created_by] [varchar](12) NULL,
[created_date] [datetime] NULL,
[modified_by] [varchar](12) NULL,
[modified_date] [datetime] NULL,
CONSTRAINT [PK_quotes] PRIMARY KEY CLUSTERED
(
[ticker] 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 [dbo].[shares](
[ticker] [char](5) NOT NULL,
[broker_id] [char](12) NOT NULL,
[quantity] [int] NOT NULL,
[created_by] [varchar](12) NOT NULL,
[created_date] [datetime] NOT NULL,
[modified_by] [varchar](12) NULL,
[modified_date] [datetime] NULL,
CONSTRAINT [PK_shares] PRIMARY KEY CLUSTERED
(
[ticker] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
ALTER TABLE [dbo].[shares] WITH CHECK ADD CONSTRAINT [FK_shares_quotes] FOREIGN KEY([ticker])
REFERENCES [dbo].[quotes] ([ticker])
ON UPDATE CASCADE
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[shares] CHECK CONSTRAINT [FK_shares_quotes]
GO
And finally this code:
string sql = "SELECT quantity, s.ticker, name, last_price FROM shares s " +
"INNER JOIN quotes q ON q.ticker = s.ticker " +
"WHERE s.ticker=#ticker AND broker_id = #broker_Id";
IEnumerable<Share> shares = connection.Query<Share, Quote, Share>(sql,
(s, q) =>
{
Share share = new Share(q, s.Quantity);
return share;
},
new { ticker = ticker, broker_Id = brokerId }
, splitOn: "ticker");
return shares.FirstOrDefault();
When I execute that query, I get the following error:
"Specified method is not supported" (???)
If I modify the sql statement by the following (with "last_price as lastPrice"):
string sql = "SELECT quantity, s.ticker, name, last_price as lastPrice FROM shares s " +
"INNER JOIN quotes q ON q.ticker = s.ticker " +
"WHERE s.ticker=#ticker AND broker_id = #broker_Id";
I get the following error:
"A parameterless default constructor or one matching signature (System.String ticker, System.String name, System.Decimal lastPrice) is required for Footstock.Domain.Model.Quote materialization"
What am I doing wrong?
For the Share class, you need to either add a parameterless constructor or one that takes only a quantity parameter.
Before Dapper calls the method that composes the result to be returned, it needs to build the parameters to pass in to (s, q) => ... In your case you need a Share and a Quote class, both of which must have a constructor that can be called using the data Dapper has. For Quote, the constructor matches the properties in the query. For Share, Dapper only has the quantity and does not have a Quote object yet.
I have the following tables that exist in my database. I am trying to set the foreign key
but I am not sure I am doing this correctly. What I have is a relationship between the
table [Application] and the table [TestAccount] where there are for example three different
[Application] rows and each will have zero or many [TestAccount] rows. I do not want to be
able to delete an [Application] row if there is already an existing [TestAccount] row.
Here's my SQL
CREATE TABLE [dbo].[Application] (
[ApplicationId] INT IDENTITY (1, 1) NOT NULL,
[Name] NVARCHAR (50) NOT NULL,
[DataVersion] ROWVERSION,
CONSTRAINT [PK_dbo.Application] PRIMARY KEY CLUSTERED ([ApplicationId] ASC)
);
CREATE TABLE [dbo].[TestAccount] (
[TestAccountId] INT IDENTITY (1, 1) NOT NULL,
[ApplicationId] INT,
[Name] NVARCHAR (50) NOT NULL,
[DataVersion] ROWVERSION,
CONSTRAINT [PK_dbo.TestAccount] PRIMARY KEY CLUSTERED ([TestAccountId] ASC),
CONSTRAINT fk_AccountApplication FOREIGN KEY (ApplicationId) REFERENCES Application(ApplicationId)
);
I am trying to configure this for EF and here's what I have so far:
modelBuilder.Entity<Application>()
HasKey(a => a.ApplicationId);
Property(a => a.ApplicationId).
HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity).
IsRequired();
modelBuilder.Entity<Application>().
Property(a => a.Name).
IsRequired().
HasMaxLength(50);
modelBuilder.Entity<TestAccount>()
HasKey(a => a.TestAccountId);
Property(a => a.TestAccountId).
HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity).
IsRequired();
modelBuilder.Entity<TestAccount>().
Property(t => t.Name).
IsRequired();
Can someone tell me if I am going about this correctly with the foreign keys in the database and also
show me how I can configure the foreign key using the fluent API.
Assuming your model looks something like this:
public class Application
{
public int ApplicationId { get; set; }
public string Name { get; set; }
public virtual ICollection<TestAccount> TestAccounts { get; set; }
}
public class TestAccount
{
public int TestAccountId { get; set; }
public int ApplicationId { get; set; }
public string Name { get; set; }
public virtual Application Application { get; set; }
}
The mapping of your FK to your navigation property via fluent would be like this:
modelBuilder.Entity<Application>()
.HasMany(a => a.TestAccounts)
.WithRequired(t => t.Application)
.WillCascadeOnDelete(false);