Related
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)
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?
In my Laravel 5.6/PostgreSQL 10.5 application
I want to save data in table :
CREATE TABLE public.rt_orders (
id serial NOT NULL,
user_id int4 NULL,
card_owner varchar(100) NOT NULL,
discount int4 NULL DEFAULT 0,
discount_code varchar(255) NULL,
qty_count int4 NOT NULL,
price_total int4 NOT NULL,
payment varchar(255) NOT NULL,
completed bool NOT NULL DEFAULT false,
error_message varchar(255) NULL,
created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
CONSTRAINT rt_orders_pkey PRIMARY KEY (id),
CONSTRAINT orders_user_id_foreign FOREIGN KEY (user_id) REFERENCES rt_users(id) ON UPDATE CASCADE ON DELETE SET NULL
)
with code :
try {
DB::beginTransaction();
$insertOrderData= [
'user_id'=> $loggedUser->id,
'card_owner'=> $card_owner,
'qty_count'=> Cart::instance('default')->count(),
'price_total'=> Cart::instance('default')->subtotal(),
'payment'=> 'stripe',
'completed'=> true
];
$newOrder = Order::create($insertOrderData);
and I got error:
SQLSTATE[22P02]: Invalid text representation: 7 ERROR: invalid input syntax for integer: "3500.75" (SQL: insert into "rt_orders" ("user_id", "card_owner", "qty_count", "price_total", "payment", "completed") values (5, gdfgdfgds, 2, 3500.75, stripe, 1) returning "id") {"userId":5,"email":"admin#mail.com","exception":"[object] (Illuminate\\Database\\QueryException(code: 22P02): SQLSTATE[22P02]: Invalid text representation: 7 ERROR: invalid input syntax for integer: \"3500.75\" (SQL: insert into \"rt_orders\" (\"user_id\", \"card_owner\", \"qty_count\", \"price_total\", \"payment\", \"completed\") values (5, gdfgdfgds, 2, 3500.75, stripe, 1) returning \"id\") at /mnt/_work_sdb8/wwwroot/lar/ArtistsRating/vendor/laravel/framework/src/Illuminate/Database/Connection.php:664, PDOException(code: 22P02): SQLSTATE[22P02]: I
Why error ?
I tried to copy the sql statement in my sql editor and payed attention that a statement like :
insert into "rt_orders" ("user_id", "card_owner", "qty_count", "price_total", "payment", "completed") values (5, fsdf, 2, 3500.75, stripe, 1)
1) Values entered as string values are without ‘’
2) and got error as last parameter was integer value not boolean:
SQL Error [42804]: ERROR: column "completed" is of type boolean but expression is of type integer
Hint: You will need to rewrite or cast the expression.
Position: 149
I tried in my model to add method:
<?php
namespace App;
use DB;
use App\MyAppModel;
use App\User;
use App\SongOrder;
class Order extends MyAppModel
{
protected $table = 'orders';
protected $primaryKey = 'id';
public $timestamps = false;
protected static function boot() {
parent::boot();
}
protected $fillable = ['user_id', 'card_owner', 'discount', 'discount_code', 'price_total', 'qty_count', 'price_total', 'payment', 'completed', 'error_message'];
public function getCompletedAttribute($value)
{
$this->debToFile(print_r($value,true),' 000 getCompletedAttribute -7 $value::');
$ret= (int)$value == 1;
$this->debToFile(print_r($ret,true),' 000 getCompletedAttribute -7 $ret::');
return $ret;
}
debToFile - is my debugging method and looks like the getCompletedAttribute is not triggered as I do not see my debigiing info of this method.
Can somebody give a hint why this error and how to fix it?
Thanks!
Your price_total has a data type is wrong
price_total int4 NOT NULL,
should be
price_total numeric(10,2) NOT NULL,
where 10 is the max total digits, and 2 is the number of digits after the decimal.
You can also use the money data type (not recommended)
price_total money NOT NULL,
Whatever you do, do NOT use any type of float.
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}
I got a problem with PostGreSQL 8.4 and tables reflection. My metadata object seems to be ok (it has foreign keys, primary keys, every columns and tables). But when I try to associate an object to an another one through a Foreign key, I get : "sqlalchemy.exc.ProgrammingError: (ProgrammingError) can't adapt type 'EventParameters' 'INSERT INTO event (".
I'm using SQLAlchemy 0.6.3 (psycopg2 2.2.1) and PostGreSQL 8.4.5
Here, my code :
#! /usr/bin/env python
from sqlalchemy import MetaData, create_engine
from sqlalchemy.orm import mapper, sessionmaker
class EventParameters(object):
pass
class Event(object):
pass
engine = create_engine('postgresql://postgres:toto#127.0.0.1:5432/renass')
metadata = MetaData()
metadata.reflect(bind=engine)
Session = sessionmaker(bind=engine)
session = Session()
mapper(EventParameters, metadata.tables['eventparameters'])
mapper(Event, metadata.tables['event'])
ep = EventParameters()
ep.publicid = 'test'
e = Event()
e.publicid = 'test'
e.eventparametersid=ep
session.add(e)
session.commit()
and my database :
CREATE TABLE EventParameters (
id SERIAL PRIMARY KEY,
publicID varchar(255) UNIQUE NOT NULL,
description varchar(255),
creationInfo_agencyID varchar(64),
creationInfo_agencyURI varchar(255),
creationInfo_author varchar(128),
creationInfo_authorURI varchar(255),
creationInfo_creationTime time,
creationInfo_version varchar(64)
);
CREATE TABLE Event (
id SERIAL PRIMARY KEY,
eventParametersID integer NOT NULL REFERENCES EventParameters(id),
publicID varchar(255) UNIQUE NOT NULL,
preferredOriginID integer,
preferredMagnitudeID integer,
preferredFocalMechanismID integer,
type EventType,
typeCertainty EventTypeCertainty,
creationInfo_agencyID varchar(64),
creationInfo_agencyURI varchar(255),
creationInfo_author varchar(128),
creationInfo_authorURI varchar(255),
creationInfo_creationTime time,
creationInfo_version varchar(64)
);
It seems that SQLAlchemy don't recognize the attribute "eventparametersid" as a relationship ...
Thank you in advance
Fabien
To make your code working you should change the mapper invocation for the Event class to include the mapping between the two classes
mapper(Event, metadata.tables['event'], properties={
'eventparameters': relation(EventParameters)
})
then use that column to assign the EventParameters instance
ep = EventParameters()
ep.publicid = 'test'
e = Event()
e.publicid = 'test'
e.eventparameters = ep