EF model not being updated correctly from database - entity-framework
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?
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)
PostgreSQL foreign key create error
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.
Entity Framework Insert - Cannot add or update a child row: a foreign key constraint fails
I'm getting the following error and despite following-up on many 'similar' posts I cannot find find the answer when making insert to 2 tables with a FK using Entity Framework. I think the issue, when looking at the Trace/Log (below) the FK (id) value is 0 (zero). If I can get that figured out it might solve the problem. ERROR: (Obvious what it is saying, but can't figure out how to fix) Cannot add or update a child row: a foreign key constraint fails ("xdata"."table_b", CONSTRAINT "f111" FOREIGN KEY ("table_a_id") REFERENCES "table_a" ("id") ON DELETE CASCADE ON UPDATE CASCADE) MODELS: public class table_a { public int id { get; set; } public string name { get; set; } } public class table_b { public int id { get; set; } public string desc { get; set; } public int table_a_id { get; set; } } CODE TO INSTANTIATE MODELS AND INSERT: table_a a = new table_a() { name = "table a name", }; table_b b = new table_b() { desc = "table b desc", table_a_id = a.id }; DataContext.Database.Log = message => Trace.Write(message); DataContext.TableA.Add(a); DataContext.TableB.Add(b); var result = DataContext.SaveChanges(); TRACE: SET SESSION sql_mode='ANSI'; INSERT INTO table_a( name) VALUES ( #gp1); SELECT id FROM table_a WHERE row_count() > 0 AND id=last_insert_id() -- #gp1: 'table a name' (Type = String, IsNullable = false, Size = 12) -- Executing at 12/8/2017 7:50:53 PM -07:00 -- Completed in 55 ms with result: EFMySqlDataReader SET SESSION sql_mode='ANSI'; INSERT INTO table_b( desc, table_a_id) VALUES ( #gp1, 0); SELECT id FROM table_b WHERE row_count() > 0 AND id=last_insert_id() -- #gp1: 'table b desc' (Type = String, IsNullable = false, Size = 12) -- Executing at 12/8/2017 7:50:53 PM -07:00 -- Failed in 56 ms with error: Cannot add or update a child row: a foreign key constraint fails ("xdata"."table_b", CONSTRAINT "f111" FOREIGN KEY ("table_a_id") REFERENCES "table_a" ("id") ON DELETE CASCADE ON UPDATE CASCADE) DB SCHEMA: Edited to remove db schema image (12/8/2017) CREATE TABLE `table_a` ( `id` int(11) NOT NULL AUTO_INCREMENT, `name` varchar(45) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `id_UNIQUE` (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8; CREATE TABLE `table_b` ( `id` int(11) NOT NULL AUTO_INCREMENT, `desc` varchar(45) DEFAULT NULL, `table_a_id` int(11) DEFAULT NULL, PRIMARY KEY (`id`), UNIQUE KEY `id_UNIQUE` (`id`), KEY `f111_idx` (`table_a_id`), CONSTRAINT `f111` FOREIGN KEY (`table_a_id`) REFERENCES `table_a` (`id`) ON DELETE CASCADE ON UPDATE CASCADE ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8;
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}