PostgreSQL foreign key create error - postgresql

I'm new to PostgreSQL and trying to create table with foreign keys.But I got error below.
create table User_Role
(
RoleId serial primary key not null,
RoleCode varchar(21),
Rolename varchar(30),
isActive bool
)
CREATE TABLE User_Account(
UserId serial primary key not null,
RoleId_ref int REFERENCES User_Role (RoleId) NULL,
Username text NULL,
Password text NULL,
IsActive bool NULL
)
CREATE TABLE User_Profile(
ProfileId serial primary key not null,
UserId_ref int REFERENCES User_Account (UserId) NULL,
RoleId_ref int REFERENCES User_Role (RoleId) NULL,
FirstName Text NULL,
LastName Text NULL,
Address Text NULL,
City varchar(100) NULL
)
first two table created successfully. But last table occur create error.
ERROR: column "roleid" referenced in foreign key constraint does not exist
SQL state: 42703
but I can't understand why.

Related

Problem with SQL workbench crash on MacOS

I'm trying to make MySQL work on my MacBook (intel CPU). I have downloaded the Server and I'm using the workbench to write the SQL. But whenever I try to make a database the workbench crashes and gives me the error:
Termination Reason: Namespace SIGNAL, Code 4 Illegal instruction: 4
Terminating Process: exc handler [933]
I have not changed any settings, it's all factory settings.
CREATE DATABASE Fisk;
USE Fisk;
create table fisk (
fisk_id int not null,
navn char(25) not null,
max_laengde_cm int not null,
primary key (fisk_id)
);
create table plads (
plads_id int not null,
navn char(25) not null,
afstand_fra_hjem_km int not null,
primary key(plads_id)
);
create table redskab(
redskab_id int not null,
navn char(25) not null,
vaegt_gram int not null,
primary key (redskab_id)
);
create table fisketur(
fisketur_id int not null,
dato date not null,
plads_id int not null,
primary key (fisketur_id),
foreign key (plads_id) references plads(plads_id)
);
create table fangst(
fangst_id int not null,
tid time not null,
laengde_cm int not null,
fisk_id int not null,
fisketur_id int not null,
redskab_id int not null,
primary key (fangst_id),
foreign key (fisk_id) references fisk(fisk_id),
foreign key (fisketur_id) references fisketur(fisketur_id),
foreign key (redskab_id) references redskab(redskab_id)
);
insert into fisk values
(1,'Hornfisk',90),
(2,'Torsk',120),
(3,'Skrubbe',50),
(4,'Makrel',45),
(5,'Laks',120);
insert into plads values
(1,'Knudshoved',31),
(2,'Vresen',45),
(3,'Fyns Hoved',48),
(4,'Gabet',24),
(5,'Kajbjerg',34);
insert into redskab values
(1,'R¯dt blink',25),
(2,'Gr¯n flue',5),
(3,'Forfang',55),
(4,'Blankt blink',35),
(5,'Gult blink',28);
insert into fisketur values
(1,'2018-10-18',4),
(2,'2019-11-23',2),
(3,'2019-06-12',3),
(4,'2019-12-11',1),
(5,'2020-01-02',1),
(6,'2014-10-14',5);
insert into fangst values
(1,'12:17:00',48,4,5,1),
(2,'15:38:00',35,3,4,3),
(3,'19:30:00',50,2,3,5),
(4,'09:28:00',41,1,2,4),
(5,'07:12:00',43,5,1,2),
(6,'05:48:00',55,1,3,2),
(7,'09:56:00',62,2,6,4);
SHOW TABLES;

MIGRATION FAILED ENUM TYPE ALREADY EXISTS ERROR

I'm building a microservices app using Spring Boot + Postgres + Flyway,
within flight-archive microservice, I created a script sql that contains the following code:
CREATE TYPE Payment_method AS ENUM ('CASH', 'PAYPAL', 'CREDIT CARD');
CREATE TABLE IF NOT EXISTS flight_booking_archive (
booking_Id INT NOT NULL PRIMARY KEY,
flight_Id INT NOT NULL,
passenger_Id INT NOT NULL,
adults INT NOT NULL,
babies INT NOT NULL,
amount_paid MONEY,
payment_method Payment_method,
booked DATE DEFAULT CURRENT_DATE,
CONSTRAINT fk_flight_id FOREIGN KEY (flight_Id) references flight(flight_ID),
CONSTRAINT fk_passenger_id FOREIGN KEY (passenger_Id) references passenger(passenger_ID)
)
then, when I run flight-archive microservice using maven, I got the following error
SQL State : 42710
Error Code : 0
Message : ERROR: type "payment_method" already exists
Location : db/migration/V1__flight_archive_table.sql (C:\Users\OMAYMA\flight-app-
demo\server\flight-booking-
archive\target\classes\db\migration\V1__flight_archive_table.sql)
Line : 1
Statement : CREATE TYPE Payment_method AS ENUM ('CASH', 'PAYPAL', 'CREDIT CARD')
In Postgres if you want to use uppercase you have to use quotation marks, otherwise, the words will always be in lowercase.
Try making this change:
CREATE TYPE "Payment_method" AS ENUM ('CASH', 'PAYPAL', 'CREDIT CARD');
CREATE TABLE IF NOT EXISTS flight_booking_archive (
booking_Id INT NOT NULL PRIMARY KEY,
flight_Id INT NOT NULL,
passenger_Id INT NOT NULL,
adults INT NOT NULL,
babies INT NOT NULL,
amount_paid MONEY,
payment_method "Payment_method",
booked DATE DEFAULT CURRENT_DATE,
CONSTRAINT fk_flight_id FOREIGN KEY (flight_Id) references flight(flight_ID),
CONSTRAINT fk_passenger_id FOREIGN KEY (passenger_Id) references passenger(passenger_ID)

EF model not being updated correctly from database

I have noted that one of my tables in my existing Entity Framework model has not been updated for long.
One table has news columns in the database which they are not present in the EF model.
Now I need to update de EF model to include these new columns in the table.
So from edmx designer I select the option "Update model from database..."
After doing that, new columns are added correctly to the table in EF model except one in which I am interested in. This column is a foreign key that points to another table.
So Why are some new columns added correctly to the EF model and the one I am interested in isn't?
UPDATE:
I am using database first. So I post here some details.
Tables in SQL Server are below:
Table [eq].[CalibracionVerificacion]
CREATE TABLE [eq].[CalibracionVerificacion](
[calibracionVerificacionId] [int] IDENTITY(1,1) NOT NULL,
[equipoId] [int] NOT NULL,
[empresaCVId] [int] NULL,
[usuarioCVMId] [int] NULL,
[tipo] [smallint] NOT NULL,
[fechaPrevista] [datetime] NULL,
[magnitudId] [nvarchar](10) NULL,
[frecuencia] [smallint] NULL,
[fechaInforme] [datetime] NULL,
[usuarioAprobadorId] [int] NULL,
[fechaAprobacion] [datetime] NULL,
[procedenciaInforme] [int] NULL,
[numeroCertificado] [varchar](25) NULL,
[temperatura] [int] NULL,
[humedadRelativa] [int] NULL,
[presionAtmosferica] [int] NULL,
[incertidumbreMaxima] [decimal](7, 2) NULL,
[correccionMedidas] [int] NULL,
[controlRealizado] [int] NULL,
[observacion] [varchar](500) NULL,
[equipoComprobacionId] [int] NULL,
[resultado] [smallint] NOT NULL,
[estado] [smallint] NOT NULL,
[fechaCalibracion] [datetime] NULL,
[unidadFrecuencia] [nvarchar](2) NULL,
CONSTRAINT [PK__Calibrac__596425FE797F8D7F] PRIMARY KEY CLUSTERED
(
[calibracionVerificacionId] 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 [eq].[CalibracionVerificacion] WITH CHECK ADD CONSTRAINT [FK_CalibracionVerificacion_Equipo] FOREIGN KEY([equipoId])
REFERENCES [eq].[Equipo] ([equipoId])
ON DELETE CASCADE
GO
ALTER TABLE [eq].[CalibracionVerificacion] CHECK CONSTRAINT [FK_CalibracionVerificacion_Equipo]
GO
ALTER TABLE [eq].[CalibracionVerificacion] WITH CHECK ADD CONSTRAINT [FK_CalibracionVerificacion_Equipo1] FOREIGN KEY([equipoComprobacionId])
REFERENCES [eq].[Equipo] ([equipoId])
GO
ALTER TABLE [eq].[CalibracionVerificacion] CHECK CONSTRAINT [FK_CalibracionVerificacion_Equipo1]
GO
Table [eq].[Equipo]
CREATE TABLE [eq].[Equipo](
[equipoId] [int] IDENTITY(1,1) NOT NULL,
[empresaPropietariaId] [int] NULL,
[sociedadId] [varchar](4) NOT NULL,
[unidadOrganizativaId] [varchar](10) NOT NULL,
[delegacionPropiedadId] [varchar](4) NULL,
[magnitudId] [nvarchar](10) NULL,
[subMagnitudId] [nvarchar](10) NULL,
[familiaId] [nvarchar](10) NULL,
[axaptaId] [varchar](10) NULL,
[denominacion] [varchar](75) NULL,
[equipoPropio] [smallint] NOT NULL,
[equipoPatron] [smallint] NOT NULL,
[usuarioSegundoResponsable] [varchar](75) NULL,
[mailSegundoResponsable] [varchar](75) NULL,
[modelo] [varchar](50) NULL,
[numeroSerie] [varchar](25) NULL,
[capacidad] [varchar](25) NULL,
[fechaAdquisicion] [datetime] NULL,
[fechaFin] [datetime] NULL,
[precioSinIva] [decimal](10, 2) NULL,
[observacion] [varchar](500) NULL,
[motivoBaja] [varchar](500) NULL,
[estado] [smallint] NOT NULL,
[equipoIdOldSocotec] [int] NULL,
[marcaId] [smallint] NULL,
[limitacion] [varchar](500) NULL,
[proveedor] [varchar](500) NULL,
[tipoId] [int] NULL,
[usuarioResponsableId] [int] NULL,
[activoFieldeas] [bit] NULL,
CONSTRAINT [PK_Equipo] PRIMARY KEY CLUSTERED
(
[equipoId] 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
Below is the generated DDL dbModel.edmx.sql. I have udpated the model from database using option "Update model from database" from model designer, but as you can see equipoId and equipoComprobacionId fields which are foreign keys are not created in the model in table [CalibracionVerificacion]. Why?
-- --------------------------------------------------
-- Dropping existing FOREIGN KEY constraints
-- --------------------------------------------------
IF OBJECT_ID(N'[eq].[FK_CalibracionVerificacion_Equipo]', 'F') IS NOT NULL
ALTER TABLE [eq].[CalibracionVerificacion] DROP CONSTRAINT [FK_CalibracionVerificacion_Equipo];
GO
IF OBJECT_ID(N'[eq].[FK_CalibracionVerificacion_Equipo1]', 'F') IS NOT NULL
ALTER TABLE [eq].[CalibracionVerificacion] DROP CONSTRAINT [FK_CalibracionVerificacion_Equipo1];
GO
IF OBJECT_ID(N'[st].[FK_EquipoUtilizado_Equipo]', 'F') IS NOT NULL
ALTER TABLE [st].[EquipoUtilizado] DROP CONSTRAINT [FK_EquipoUtilizado_Equipo];
GO
-- --------------------------------------------------
-- Dropping existing tables
-- --------------------------------------------------
IF OBJECT_ID(N'[eq].[CalibracionVerificacion]', 'U') IS NOT NULL
DROP TABLE [eq].[CalibracionVerificacion];
GO
IF OBJECT_ID(N'[eq].[Equipo]', 'U') IS NOT NULL
DROP TABLE [eq].[Equipo];
GO
IF OBJECT_ID(N'[st].[EquipoUtilizado]', 'U') IS NOT NULL
DROP TABLE [st].[EquipoUtilizado];
GO
-- --------------------------------------------------
-- Creating all tables
-- --------------------------------------------------
-- Creating table 'Equipo'
CREATE TABLE [dbo].[Equipo] (
[equipoId] int IDENTITY(1,1) NOT NULL,
[empresaPropietariaId] int NULL,
[sociedadId] varchar(4) NOT NULL,
[unidadOrganizativaId] varchar(10) NOT NULL,
[magnitudId] nvarchar(10) NULL,
[subMagnitudId] nvarchar(10) NULL,
[familiaId] nvarchar(10) NULL,
[axaptaId] varchar(10) NULL,
[denominacion] varchar(75) NULL,
[equipoPropio] smallint NOT NULL,
[equipoPatron] smallint NOT NULL,
[usuarioSegundoResponsable] varchar(75) NULL,
[mailSegundoResponsable] varchar(75) NULL,
[modelo] varchar(50) NULL,
[numeroSerie] varchar(25) NULL,
[capacidad] varchar(25) NULL,
[fechaAdquisicion] datetime NULL,
[fechaFin] datetime NULL,
[precioSinIva] decimal(10,2) NULL,
[observacion] varchar(500) NULL,
[motivoBaja] varchar(500) NULL,
[estado] smallint NOT NULL,
[equipoIdOldSocotec] int NULL,
[marcaId] smallint NULL,
[limitacion] varchar(500) NULL,
[proveedor] varchar(500) NULL,
[delegacionPropiedadId] varchar(4) NULL,
[tipoId] int NULL,
[usuarioResponsableId] int NULL,
[activoFieldeas] bit NULL
);
GO
-- Creating table 'EquipoUtilizado'
CREATE TABLE [dbo].[EquipoUtilizado] (
[equipoUtilizadoId] int IDENTITY(1,1) NOT NULL,
[seguimientoTrabajoId] int NOT NULL,
[mantenimiento] bit NULL,
[orden] tinyint NULL,
[Equipo_equipoId] int NOT NULL
);
GO
-- Creating table 'CalibracionVerificacion'
CREATE TABLE [dbo].[CalibracionVerificacion] (
[calibracionVerificacionId] int IDENTITY(1,1) NOT NULL,
[empresaCVId] int NULL,
[usuarioCVMId] int NULL,
[tipo] smallint NOT NULL,
[fechaPrevista] datetime NULL,
[magnitudId] nvarchar(10) NULL,
[frecuencia] smallint NULL,
[fechaInforme] datetime NULL,
[usuarioAprobadorId] int NULL,
[fechaAprobacion] datetime NULL,
[procedenciaInforme] int NULL,
[numeroCertificado] varchar(25) NULL,
[temperatura] int NULL,
[humedadRelativa] int NULL,
[presionAtmosferica] int NULL,
[incertidumbreMaxima] decimal(7,2) NULL,
[correccionMedidas] int NULL,
[controlRealizado] int NULL,
[observacion] varchar(500) NULL,
[resultado] smallint NOT NULL,
[estado] smallint NOT NULL,
[fechaCalibracion] datetime NULL,
[unidadFrecuencia] nvarchar(2) NULL,
[Equipo_equipoId] int NOT NULL,
[Equipo1_equipoId] int NULL
);
GO
-- --------------------------------------------------
-- Creating all PRIMARY KEY constraints
-- --------------------------------------------------
-- Creating primary key on [equipoId] in table 'Equipo'
ALTER TABLE [dbo].[Equipo]
ADD CONSTRAINT [PK_Equipo]
PRIMARY KEY CLUSTERED ([equipoId] ASC);
GO
-- Creating primary key on [equipoUtilizadoId] in table 'EquipoUtilizado'
ALTER TABLE [dbo].[EquipoUtilizado]
ADD CONSTRAINT [PK_EquipoUtilizado]
PRIMARY KEY CLUSTERED ([equipoUtilizadoId] ASC);
GO
-- Creating primary key on [calibracionVerificacionId] in table 'CalibracionVerificacion'
ALTER TABLE [dbo].[CalibracionVerificacion]
ADD CONSTRAINT [PK_CalibracionVerificacion]
PRIMARY KEY CLUSTERED ([calibracionVerificacionId] ASC);
GO
-- --------------------------------------------------
-- Creating all FOREIGN KEY constraints
-- --------------------------------------------------
-- Creating foreign key on [Equipo_equipoId] in table 'EquipoUtilizado'
ALTER TABLE [dbo].[EquipoUtilizado]
ADD CONSTRAINT [FK_EquipoUtilizado_Equipo]
FOREIGN KEY ([Equipo_equipoId])
REFERENCES [dbo].[Equipo]
([equipoId])
ON DELETE NO ACTION ON UPDATE NO ACTION;
GO
-- Creating non-clustered index for FOREIGN KEY 'FK_EquipoUtilizado_Equipo'
CREATE INDEX [IX_FK_EquipoUtilizado_Equipo]
ON [dbo].[EquipoUtilizado]
([Equipo_equipoId]);
GO
-- Creating foreign key on [Equipo_equipoId] in table 'CalibracionVerificacion'
ALTER TABLE [dbo].[CalibracionVerificacion]
ADD CONSTRAINT [FK_CalibracionVerificacion_Equipo]
FOREIGN KEY ([Equipo_equipoId])
REFERENCES [dbo].[Equipo]
([equipoId])
ON DELETE CASCADE ON UPDATE NO ACTION;
GO
-- Creating non-clustered index for FOREIGN KEY 'FK_CalibracionVerificacion_Equipo'
CREATE INDEX [IX_FK_CalibracionVerificacion_Equipo]
ON [dbo].[CalibracionVerificacion]
([Equipo_equipoId]);
GO
-- Creating foreign key on [Equipo1_equipoId] in table 'CalibracionVerificacion'
ALTER TABLE [dbo].[CalibracionVerificacion]
ADD CONSTRAINT [FK_CalibracionVerificacion_Equipo1]
FOREIGN KEY ([Equipo1_equipoId])
REFERENCES [dbo].[Equipo]
([equipoId])
ON DELETE NO ACTION ON UPDATE NO ACTION;
GO
-- Creating non-clustered index for FOREIGN KEY 'FK_CalibracionVerificacion_Equipo1'
CREATE INDEX [IX_FK_CalibracionVerificacion_Equipo1]
ON [dbo].[CalibracionVerificacion]
([Equipo1_equipoId]);
GO
So as above explained, since equipoId and equipoComprobacionId fields which are foreign keys are not created in the model in table [CalibracionVerificacion], then below Linq query are not working, that is, fechaPrevista is getting Nothing because c3.equipoId and c.equipoId are always 0 because equipoId field is always 0 and not present in table CalibracionVerificacion. So the problem is that equipoId field in CalibracionVerificacion table is never being loaded in the model. Why?
Dim eq = db.Equipo
For Each equipo As Equipo In eq
Dim fechaPrevista As DateTime? = If(Not (equipo.CalibracionVerificacion.Any()) OrElse
Not (equipo.CalibracionVerificacion.Any(Function(x) Not (String.IsNullOrWhiteSpace(x.magnitudId)))),
CType(Nothing, DateTime?),
(From c In equipo.CalibracionVerificacion
Join c2 In
(From c3 In equipo.CalibracionVerificacion
Where c3.equipoId = equipo.equipoId AndAlso Not (String.IsNullOrWhiteSpace(c3.magnitudId))
Group c3 By c3.magnitudId Into cgroup = Group
Select New With
{
Key .MagnitudID = magnitudId,
Key .MaxDate = cgroup.Max(Function(x) x.fechaPrevista)
}
) On New With {.JoinProperty1 = c.magnitudId, .JoinProperty2 = c.fechaPrevista} Equals
New With {.JoinProperty1 = c2.MagnitudID, .JoinProperty2 = c2.MaxDate}
Where c.equipoId = equipo.equipoId
Select c).Min(Function(d) d.fechaPrevista))
Next
LAST ATTEMPT:
From model designer I have deleted all the tables. Then I have gone through option "Update model from database..." and I have selected "Add" tab. Finally I select the tables above indicated which I am interested in and all three tables are inserted correctly into the model edmx, also equipoId and equipoComprobacionId fields are added correctly into table [CalibracionVerificacion]. Relations between tables are created correctly as well. Finally I successfully build the solution and execute it. I put a breakpoint in the above LINQ expression to debug it, after pressing F10 to proceed with its execution an exception is thrown saying this:
{"Schema specified is not valid. Errors: The relationship
'MyModel.FK_CalibracionVerificacion_Equipo' was not loaded because the
type 'MyModel.CalibracionVerificacion' is not available. The following
information may be useful in resolving the previous error: The
required property 'equipoComprobacionId' does not exist on the type
'MyService.CalibracionVerificacion'.
The relationship 'MyModel.FK_CalibracionVerificacion_Equipo1' was not
loaded because the type 'MyModel.CalibracionVerificacion' is not
available. The following information may be useful in resolving the
previous error: The required property 'equipoComprobacionId' does not
exist on the type 'MyService.CalibracionVerificacion'.
"}
Below are the entities generated by EF:
Partial Public Class Equipo
Public Property equipoId As Integer
Public Property empresaPropietariaId As Nullable(Of Integer)
Public Property sociedadId As String
Public Property unidadOrganizativaId As String
Public Property delegacionPropiedadId As String
Public Property magnitudId As String
Public Property subMagnitudId As String
Public Property familiaId As String
Public Property axaptaId As String
Public Property denominacion As String
Public Property equipoPropio As Short
Public Property equipoPatron As Short
Public Property usuarioSegundoResponsable As String
Public Property mailSegundoResponsable As String
Public Property modelo As String
Public Property numeroSerie As String
Public Property capacidad As String
Public Property fechaAdquisicion As Nullable(Of Date)
Public Property fechaFin As Nullable(Of Date)
Public Property precioSinIva As Nullable(Of Decimal)
Public Property observacion As String
Public Property motivoBaja As String
Public Property estado As Short
Public Property equipoIdOldSocotec As Nullable(Of Integer)
Public Property marcaId As Nullable(Of Short)
Public Property limitacion As String
Public Property proveedor As String
Public Property tipoId As Nullable(Of Integer)
Public Property usuarioResponsableId As Nullable(Of Integer)
Public Property activoFieldeas As Nullable(Of Boolean)
Public Overridable Property CalibracionVerificacion As ICollection(Of CalibracionVerificacion) = New HashSet(Of CalibracionVerificacion)
Public Overridable Property CalibracionVerificacion1 As ICollection(Of CalibracionVerificacion) = New HashSet(Of CalibracionVerificacion)
Public Overridable Property EquipoUtilizado As ICollection(Of EquipoUtilizado) = New HashSet(Of EquipoUtilizado)
End Class
Partial Public Class CalibracionVerificacion
Public Property calibracionVerificacionId As Integer
Public Property equipoId As Integer
Public Property empresaCVId As Nullable(Of Integer)
Public Property usuarioCVMId As Nullable(Of Integer)
Public Property tipo As Short
Public Property fechaPrevista As Nullable(Of Date)
Public Property magnitudId As String
Public Property frecuencia As Nullable(Of Short)
Public Property fechaInforme As Nullable(Of Date)
Public Property usuarioAprobadorId As Nullable(Of Integer)
Public Property fechaAprobacion As Nullable(Of Date)
Public Property procedenciaInforme As Nullable(Of Integer)
Public Property numeroCertificado As String
Public Property temperatura As Nullable(Of Integer)
Public Property humedadRelativa As Nullable(Of Integer)
Public Property presionAtmosferica As Nullable(Of Integer)
Public Property incertidumbreMaxima As Nullable(Of Decimal)
Public Property correccionMedidas As Nullable(Of Integer)
Public Property controlRealizado As Nullable(Of Integer)
Public Property observacion As String
Public Property equipoComprobacionId As Nullable(Of Integer)
Public Property resultado As Short
Public Property estado As Short
Public Property fechaCalibracion As Nullable(Of Date)
Public Property unidadFrecuencia As String
Public Overridable Property Equipo As Equipo
Public Overridable Property Equipo1 As Equipo
End Class
What's happening?

Using Automapper with F# Entity Type Provider

I am looking at Automapper for the first time using F# and the Entity Type Provider. I want to map between the EF Type Provider types and the F# record types that I have created.
The EF Type Provider is based on the following database schema:
CREATE TABLE [dbo].[Address](
[Id] [int] IDENTITY(1,1) NOT NULL,
[FamilyId] [int] NOT NULL,
[State] [varchar](50) NOT NULL,
[County] [varchar](50) NOT NULL,
[City] [varchar](50) NOT NULL,
CONSTRAINT [PK_Address] PRIMARY KEY CLUSTERED ([Id] ASC)
CREATE TABLE [dbo].[Child](
[Id] [int] IDENTITY(1,1) NOT NULL,
[FamilyId] [int] NOT NULL,
[FirstName] [varchar](50) NOT NULL,
[Gender] [varchar](50) NOT NULL,
[Grade] [int] NOT NULL,
CONSTRAINT [PK_Child] PRIMARY KEY CLUSTERED ([Id] ASC)
CREATE TABLE [dbo].[Family](
[Id] [int] IDENTITY(1,1) NOT NULL,
[LastName] [varchar](50) NOT NULL,
[IsRegistered] [bit] NOT NULL,
CONSTRAINT [PK_Family] PRIMARY KEY CLUSTERED ([Id] ASC)
CREATE TABLE [dbo].[Parent](
[Id] [int] IDENTITY(1,1) NOT NULL,
[FamilyId] [int] NOT NULL,
[FirstName] [varchar](50) NOT NULL,
CONSTRAINT [PK_Parent] PRIMARY KEY CLUSTERED ([Id] ASC)
CREATE TABLE [dbo].[Pet](
[Id] [int] IDENTITY(1,1) NOT NULL,
[ChildId] [int] NOT NULL,
[GivenName] [varchar](50) NOT NULL,
CONSTRAINT [PK_Pet] PRIMARY KEY CLUSTERED ([Id] ASC)
ALTER TABLE [dbo].[Address] WITH CHECK ADD CONSTRAINT [FK_Address_Family] FOREIGN KEY([FamilyId])
REFERENCES [dbo].[Family] ([Id])
ALTER TABLE [dbo].[Address] CHECK CONSTRAINT [FK_Address_Family]
ALTER TABLE [dbo].[Child] WITH CHECK ADD CONSTRAINT [FK_Child_Family] FOREIGN KEY([FamilyId])
REFERENCES [dbo].[Family] ([Id])
ALTER TABLE [dbo].[Child] CHECK CONSTRAINT [FK_Child_Family]
ALTER TABLE [dbo].[Parent] WITH CHECK ADD CONSTRAINT [FK_Parent_Family] FOREIGN KEY([FamilyId])
REFERENCES [dbo].[Family] ([Id])
ALTER TABLE [dbo].[Parent] CHECK CONSTRAINT [FK_Parent_Family]
ALTER TABLE [dbo].[Pet] WITH CHECK ADD CONSTRAINT [FK_Pet_Child] FOREIGN KEY([ChildId])
REFERENCES [dbo].[Child] ([Id])
ALTER TABLE [dbo].[Pet] CHECK CONSTRAINT [FK_Pet_Child]
I then created a comparable set of types in F#:
type Pet = {Id:int; GivenName:string}
type Child = {Id:int; FirstName:string; Gender:string; Grade:int; Pets: Pet list}
type Address = {Id:int; State:string; County:string; City:string}
type Parent = {Id:int; FirstName:string}
type Family = {Id:int; Parents:Parent list; Children: Child list; Address:Address}
The only real difference is that the foreign key is not explicit in the record types.
When I use Automapper on the Address type, it works as expected:
Mapper.CreateMap<EntityConnection.ServiceTypes.Address, Address>()
let context = EntityConnection.GetDataContext()
let addressQuery = query {for address in context.Addresses do select address}
let address = Seq.head addressQuery
let address' = Mapper.Map<Address>(address)
val address' : Address = {Id = 1;
State = "WA";
County = "King";
City = "Seattle";}
But when I try and do the same with the entire graph,
Mapper.CreateMap<EntityConnection.ServiceTypes.Pet, Pet>()
Mapper.CreateMap<EntityConnection.ServiceTypes.Child, Child>()
Mapper.CreateMap<EntityConnection.ServiceTypes.Address, Address>()
Mapper.CreateMap<EntityConnection.ServiceTypes.Parent, Parent>()
Mapper.CreateMap<EntityConnection.ServiceTypes.Family, Family>()
let context = EntityConnection.GetDataContext()
let familyQuery = query {for family in context.Families do select family}
let family = Seq.head familyQuery
let family' = Mapper.Map<Family>(family)
I get this exception:
System.ArgumentException: Type needs to have a constructor with 0 args or only optional args
Parameter name: type
I am wondering if it is b/c EF is lazy loading so the remaining types are not being evaluated? has anyone seen this before?
The error is pretty straight forward. None of your classes have a constructor that takes 0 arguments.
F# creates default constructors for you so the default constructor on your class has multiple arguments in it. For example:
type Pet = {Id:int; GivenName:string}
as a c# class would have this as it's definition.
public class Pet
{
public int Id { get; private set; }
public string GivenName { get; private set; }
public Pet(int id, string givenName)
{
Id = id;
GivenName = givenName;
}
}
Note the lack of a parameterless constructor. That's where your error is coming from.
You can fix it by flagging your type as CLIMutable
[<CLIMutable>]
type Pet = {Id:int; GivenName:string}

ADO.NET entity data model deleting many rows

I have following structure of the database
CREATE TABLE IF NOT EXISTS `klienci` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`nazwa` varchar(50) NOT NULL,
`miejscowosc` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
CREATE TABLE IF NOT EXISTS `klienci_do_trasy` (
`klient_id` int(11) NOT NULL,
`trasa_id` int(11) NOT NULL,
`seq` int(11) NOT NULL,
PRIMARY KEY (`klient_id`,`trasa_id`),
KEY `trasa_id` (`trasa_id`),
KEY `klient_id` (`klient_id`,`trasa_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE IF NOT EXISTS `trasy` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`nazwa` varchar(50) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
ALTER TABLE `klienci_do_trasy`
ADD CONSTRAINT `klienci_do_trasy_ibfk_5` FOREIGN KEY (`klient_id`) REFERENCES `klienci` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION,
ADD CONSTRAINT `klienci_do_trasy_ibfk_6` FOREIGN KEY (`trasa_id`) REFERENCES `trasy` (`id`) ON DELETE NO ACTION ON UPDATE NO ACTION;
And I would like to run query similar to:
DELETE FROM klienci_do_trasy WHERE klient_id = 1;
Don't know how to do this with ADO.NET entity
With EntityFramework v1.0 there is no such a possibility. You would have to call ObjectContext.DeleteObject for each entity:
using (TheDataContext entities = new TheDataContext())
{
List<Klienci_do_tracy> kdcList = //get entities to delete
foreach(Klienci_do_tracy kdc in kdcList)
{
entities.DeleteObject(kdc);
}
entities.SaveChanges();
}
or you could use EntityCommand to do that on old fashion way.
[update: run native sql with EF]
var eConnection = (System.Data.EntityClient.EntityConnection)yourContextInstance.Connection;
DbConnection conn = eConnection.StoreConnection;
if (conn.State != ConnectionState.Open)
conn.Open();
using (DbCommand cmd = conn.CreateCommand())
{
//write native sql query
cmd.CommandText = "delete from...where...";
cmd.ExecuteNonQuery();
}
You would probably have to wrap this in try finally to ensure closing connection if something goes wrong and additional checks on connestion state.