Error saving row in Postgres and how to fix it? - postgresql

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.

Related

Why does mybatis not mapping date to Localate?

Here's my code
interface Mapper {
#Select("select * from tb_user")
fun list():List<Map<String,Any>>
}
val build = SqlSessionFactoryBuilder().build(configuration).openSession().getMapper(Mapper::class.java)
var list = build.list()
I have a column of type date, but mybatis will mapping it to java.sql.date。
I checked the source code,Found out that is the reason why ResultSet.ResultSetMetaData.getColumnClassName() returns java.sql.date,but if the type is datetime, getColumnClassName returns Localdatetime。
Why can't java 8 types be unified,What will happen if you do。
The version is as follows
mybatis:3.5.11
mysql-jdbc:8.0.30
mysql:8.0.31
CREATE TABLE `tb_user` (
`user_email` varchar(100) DEFAULT NULL,
`user_name` varchar(100) DEFAULT NULL,
`user_passwd` varchar(100) DEFAULT NULL,
`year_test` date DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;

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)

What is Causing this Dart Sq3Lite Database Exception Error?

Thank you in advance for your help.
This issue has been driving me crazy for the past couple of days. I have searched every site that Google has returned and still the resolutions haven't helped.
I am attempting to create a Sq3Lite database using Dart and keeping getting a DatabaseException error when trying to create a table that uses foreign keys. I've tried turning foreign key use on with 'PRAGMA foreign_keys = ON' as well but no luck. I am also using an IOS simulator in Android Studio and delete the app before running the code with attempted fixes.
Here is my code:
final int version = 1;
Database db;
Future<Database> openDb() async {
if (db == null) {
db = await openDatabase(join(await getDatabasesPath(), 'skeema.db'), onCreate: (database, version) {
database.execute('CREATE TABLE Account(id INTEGER PRIMARY KEY, Name TEXT NOT NULL, CurrencyType TEXT NOT NULL, ' + 'Balance REAL NOT NULL, IsPrimary TEXT NULL)');
database.execute('CREATE TABLE BudgetItem(id INTEGER PRIMARY KEY, Name TEXT NOT NULL, Icon TEXT NOT NULL, Budget REAL NOT NULL, ' + 'IsPrimary TEXT NULL)');
database.execute('CREATE TABLE TransactionType(id INTEGER PRIMARY KEY, Type TEXT NOT NULL)');
database.execute('CREATE TABLE Transaction(id INTEGER PRIMARY KEY, Account_id INTEGER NOT NULL, BudgetItem_id INTEGER NOT NULL, ' +
'TransactionType_id INTEGER NOT NULL, Amount REAL NOT NULL, Date TEXT NOT NULL, Party TEXT NOT NULL, Note TEXT NULL, ' +
'FOREIGN KEY(Account_id) REFERENCES Account(id), ' +
'FOREIGN KEY(BudgetItem_id) REFERENCES BudgetItem(id), ' +
'FOREIGN KEY(TransactionType_id) REFERENCES TransactionType(id))');
}, version: version);
}
return db;
}
Here is the error:
[VERBOSE-2:ui_dart_state.cc(157)] Unhandled Exception: DatabaseException(Error Domain=FMDatabase Code=1 "near "Transaction": syntax error" UserInfo={NSLocalizedDescription=near "Transaction": syntax error}) sql 'CREATE TABLE Transaction(id INTEGER PRIMARY KEY, Account_id INTEGER NOT NULL, BudgetItem_id INTEGER NOT NULL, TransactionType_id INTEGER NOT NULL, Amount REAL NOT NULL, Date TEXT NOT NULL, Party TEXT NOT NULL, Note TEXT NULL, FOREIGN KEY(Account_id) REFERENCES Account(id), FOREIGN KEY(BudgetItem_id) REFERENCES BudgetItem(id), FOREIGN KEY(TransactionType_id) REFERENCES TransactionType(id))' args []}
#0 wrapDatabaseException (package:sqflite/src/exception_impl.dart:11:7)
<asynchronous suspension>
#1 SqfliteDatabaseFactoryImpl.wrapDatabaseException (package:sqflite/src/factory_impl.dart:27:7)
#2 SqfliteDatabaseMixin.safeInvokeMethod (package:sqflite_common/src/database_mixin.dart:208:15)
#3 SqfliteDatabaseMixin.invokeExecute (package:sqflite_common/src/database_mixin.dart:370<…>
The first 3 tables get created successfully every time but the last table throws the error. Any help is greatly appreciated.
Thank you.
Transaction is a Sq3Lite keyword, so you can't name your table that. So give it any other name and it will work.
There may be ways to use that name anyway if you escape it, but the easy solution is just to choose a different name.
List of all keywords: https://www.sqlite.org/lang_keywords.html

ERROR: column "urls" is of type url[] but expression is of type record[]

ddl
CREATE TYPE url AS (
url varchar,
status int4);
CREATE TABLE public.tiantang_page (
href varchar NOT NULL,
status int4 NOT NULL,
description varchar NOT NULL,
urls url[] NULL,
urltest url NULL
);
sql
INSERT INTO public.tiantang_page
(href, status, description, urls, urltest)
VALUES('', 0, '', array[row('test',0)], row('test',0));
error
SQL Error [42804]: ERROR: column "urls" is of type url[] but expression is of type record[]
Hint: You will need to rewrite or cast the expression.
Position: 97
As per the error message, you'll need to cast back to your composite url type using ::
INSERT INTO public.tiantang_page
(href, status, description, urls, urltest)
VALUES('', 0, '', array[row('test',0)::url], row('test',0)::url);
SqlFiddle

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?