Make T4 reverse POCO generate classes properly - entity-framework

I am using a project which has T4MVC generating classes from a database table. I have several issues but this seems to be a pattern with them. I have not posted the .tt file because it is pretty large.
for example
HasRequired(a => a.AccountPaymentSettingId).WithMany(b => b.CustomerFileTypeAccountPaymentSettingFlexibles).HasForeignKey(c => c.AccountPaymentSettingId);
has a => a.AccountPaymentSettingId and I want a => a.AccountPaymentSetting
Here is the top of the .tt file to show the version
<## include file="..\\EF.Reverse.POCO.Core.ttinclude" #>
<#
// v2.17.1
It is not using desired names in the generated code.
This is what is generated:
public CustomerFileTypeAccountPaymentSettingFlexibleConfiguration(string schema)
{
ToTable(schema + ".Customer_FileType_Account_Payment_Setting_Flexible");
HasKey(x => x.AccountPaymentSettingFlexibleId);
Property(x => x.AccountPaymentSettingFlexibleId).HasColumnName("Account_Payment_Setting_Flexible_ID").IsRequired().HasColumnType("int").HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(x => x.AccountPaymentSettingId).HasColumnName("Account_Payment_Setting_ID").IsRequired().HasColumnType("int");
Property(x => x.PaymentMethod).HasColumnName("Payment_Method").IsRequired().IsUnicode(false).HasColumnType("varchar").HasMaxLength(5);
Property(x => x.Priority).HasColumnName("Priority").IsRequired().HasColumnType("int");
Property(x => x.RowCreatedDate).HasColumnName("RowCreatedDate").IsRequired().HasColumnType("datetime2");
HasRequired(a => a.AccountPaymentSettingId).WithMany(b => b.CustomerFileTypeAccountPaymentSettingFlexibles).HasForeignKey(c => c.AccountPaymentSettingId);
HasRequired(a => a.PaymentMethod).WithMany(b => b.CustomerFileTypeAccountPaymentSettingFlexibles).HasForeignKey(c => c.PaymentMethod);
InitializePartial();
}
and this is my desired results:
public CustomerFileTypeAccountPaymentSettingFlexibleConfiguration(string schema)
{
ToTable(schema + ".Customer_FileType_Account_Payment_Setting_Flexible");
HasKey(x => x.AccountPaymentSettingFlexibleId);
Property(x => x.AccountPaymentSettingFlexibleId).HasColumnName("Account_Payment_Setting_Flexible_ID").IsRequired().HasColumnType("int").HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
Property(x => x.AccountPaymentSettingId).HasColumnName("Account_Payment_Setting_ID").IsRequired().HasColumnType("int");
Property(x => x.PaymentMethodCode).HasColumnName("Payment_Method").IsRequired().IsUnicode(false).HasColumnType("varchar").HasMaxLength(5);
Property(x => x.Priority).HasColumnName("Priority").IsRequired().HasColumnType("int");
HasRequired(a => a.AccountPaymentSetting).WithMany(b => b.CustomerFileTypeAccountPaymentSettingFlexibles).HasForeignKey(c => c.AccountPaymentSettingId);
HasRequired(a => a.PaymentMethod).WithMany(b => b.CustomerFileTypeAccountPaymentSettingFlexibles).HasForeignKey(c => c.PaymentMethodCode);
InitializePartial();
}
Just for completeness, this is the relevant part of the table (I left off some default and FK constraints to keep it compact)
CREATE TABLE [dbo].[Customer_FileType_Account_Payment_Setting_Flexible](
[Account_Payment_Setting_Flexible_ID] [int] IDENTITY(1,1) NOT NULL,
[Account_Payment_Setting_ID] [int] NOT NULL,
[Payment_Method] [varchar](5) NOT NULL,
[Priority] [int] NOT NULL,
[RowCreatedDate] [datetime2](7) NOT NULL,
CONSTRAINT [PK_Customer_FileType_Account_Payment_Setting_Flexible] PRIMARY KEY CLUSTERED
(
[Account_Payment_Setting_Flexible_ID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PayspanHealth_Data3],
CONSTRAINT [UK_CustomerFileTypeAccountPaymentSettingFlexible_SettingId_PaymentMethod] UNIQUE NONCLUSTERED
(
[Account_Payment_Setting_ID] ASC,
[Payment_Method] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PayspanHealth_Data3],
CONSTRAINT [UK_CustomerFileTypeAccountPaymentSettingFlexible_SettingId_Priority] UNIQUE NONCLUSTERED
(
[Account_Payment_Setting_ID] ASC,
[Priority] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PayspanHealth_Data3]
) ON [PayspanHealth_Data3]
GO
ALTER TABLE [dbo].[Customer_FileType_Account_Payment_Setting_Flexible] ADD CONSTRAINT [DF_CustomerFileTypeAccountPaymentSettingFlexible_RowCreatedDate] DEFAULT (sysdatetime()) FOR [RowCreatedDate]
GO
ALTER TABLE [dbo].[Customer_FileType_Account_Payment_Setting_Flexible] WITH CHECK ADD CONSTRAINT [FK_CustomerFileTypeAccountPaymentSettingFlexible_AccountPaymentSettingId] FOREIGN KEY([Account_Payment_Setting_ID])
REFERENCES [dbo].[Customer_FileType_Account_Payment_Settings] ([Account_Payment_Setting_ID])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Customer_FileType_Account_Payment_Setting_Flexible] CHECK CONSTRAINT [FK_CustomerFileTypeAccountPaymentSettingFlexible_AccountPaymentSettingId]
GO
ALTER TABLE [dbo].[Customer_FileType_Account_Payment_Setting_Flexible] WITH CHECK ADD CONSTRAINT [FK_CustomerFileTypeAccountPaymentSettingFlexible_PaymentMethod] FOREIGN KEY([Payment_Method])
REFERENCES [dbo].[Payment_Method] ([Payment_Method_Code])
GO
ALTER TABLE [dbo].[Customer_FileType_Account_Payment_Setting_Flexible] CHECK CONSTRAINT [FK_CustomerFileTypeAccountPaymentSettingFlexible_PaymentMethod]
GO

Related

Entity Framework 'properties expression is not valid' when mapping table

Table definition:
CREATE TABLE [Index].[Dependency] (
[RevisionId] INT NOT NULL,
[MapCode] VARCHAR (10) NOT NULL,
[GroupId] SMALLINT NOT NULL,
[DependencyTypeId] TINYINT NOT NULL,
[InputThreshold] DECIMAL (9, 2) NOT NULL,
[InjectMapCode] VARCHAR (10) NULL,
[InjectAmount] DECIMAL (9, 2) NOT NULL,
CONSTRAINT [UQ_Dependency_RevisionId_MapCode_GroupId] UNIQUE NONCLUSTERED ([RevisionId] ASC, [MapCode] ASC, [GroupId] ASC),
CONSTRAINT [FK_Dependency_MapCode] FOREIGN KEY ([MapCode]) REFERENCES [Index].[Material] ([MapCode]),
CONSTRAINT [FK_Dependency_InjectMapCode] FOREIGN KEY ([InjectMapCode]) REFERENCES [Index].[Material] ([MapCode]),
CONSTRAINT [FK_Dependency_Revision] FOREIGN KEY ([RevisionId]) REFERENCES [Index].[DependencyRevision] ([DependencyRevisionId]),
CONSTRAINT [FK_Dependency_DependencyType] FOREIGN KEY ([DependencyTypeId]) REFERENCES [Index].[DependencyType] ([DependencyTypeId]),
CONSTRAINT [FK_Dependency_Group] FOREIGN KEY ([GroupId]) REFERENCES [Index].[Group] ([GroupId])
);
My attempt to map to it:
public class DependencyMap : EntityTypeConfiguration<Entities.Dependency>
{
public DependencyMap()
{
ToTable("Dependency", "Index");
HasKey(md => new { md.RevisionId, md.MapCode, md.GroupId });
Property(s => s.RevisionId).IsRequired().HasColumnName("RevisionId");
Property(s => s.MapCode).IsRequired().HasMaxLength(10).HasColumnName("MapCode");
Property(s => s.GroupId).IsRequired().HasColumnName("GroupId");
Property(s => s.DependencyTypeId).IsRequired().HasColumnName("DependencyId");
Property(s => s.InputThreshold).IsRequired().HasColumnName("InputThreshold").HasPrecision(9, 2);
Property(s => s.InjectMapCode).IsOptional().HasColumnName("InjectEngineMapCode").HasMaxLength(10);
Property(s => s.InjectAmount).HasColumnName("InjectAmount").IsRequired().HasPrecision(9, 2);
}
}
When I try to call a method that retrieves from the table an exception is thrown on
'HasKey(md => new { md.RevisionId, md.MapCode, md.GroupId })'
saying that 'properties expression is not valid. The expression should represent a property' when mapping the table. If anyone could show me how to properly map a table like this without explicitly defined primary key it would be much appreciated. Thanks.

How to populate backend select with records from a static database table in Typo3 CMS 6.2

-- Typo3 CMS version 6.2 --
I have some entities which have a country property.
In the backend, when inserting/editing one of such entities I would like to be able to pick the country from a select.
As different entity types all share the same countries I thought it would be appropriate to store the countries in a db table. Then the countries are not going to be modified via the backend, so I don't need an admin interface for them.
Can this be achieved? How?
Up until now this is what I've come up with in my TCA configuration for one of my entities...
'country' => array(
'exclude' => 1,
'label' => 'LLL:EXT:ape/Resources/Private/Language/locallang_db.xlf:tx_myext_domain_model_building.country',
'config' => array(
'type' => 'select',
'foreign_table' => 'tx_myext_countries',
'size' => 1,
'maxitems' => 1,
'eval' => 'required'
),
)
...and this is the countries table sql...
CREATE TABLE tx_myext_countries (
uid int(11) NOT NULL auto_increment,
pid int(11),
name varchar(30) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
code varchar(3) COLLATE utf8_unicode_ci NOT NULL DEFAULT '',
PRIMARY KEY (uid)
);
...but while not giving any error it displays an empty select in the backend.
What am I missing?
Should I create a model for the countries? Should I treat them as entities? Would it be appropriate to configure it as an external data source?
Any help greatly appreciated!
Update
This is my attempt at configuring the tx_myext_countries table in TCA:
$GLOBALS['TCA']['tx_myext_countries'] = array(
'ctrl' => array(
'title' => 'Country',
'label' => 'name',
'searchFields' => 'name,code,',
),
);

PostgreSQL column does not exist when it does

I have the following PostgreSQL query...
WITH update_parts (id,id_finish)
AS (VALUES (1,42), (2,42), (3,30), (4,30))
UPDATE parts SET id = up.id, id_metal = up.id_metal
FROM update_parts up WHERE up.id = parts.id;
...and I get the error...
column up.id_metal does not exist LINE 1
I have verified I'm connected to the correct database, to the correct table and that the column exists. I'm only partially certain about permissions which I set via the following...
GRANT ALL(id_metal) ON parts TO public;
...and...
GRANT ALL(id_metal) ON parts TO postgres;
I plan to limit the permissions to SELECT, UPDATE, DELETE and INSERT after I've figured out the problem. For clarification it is the "parts" table and the "id_metal" column.
How do I resolve this error and UPDATE the rows?
After updating the permissions I'm not sure what else to consider?
I used the following query to get information about the column...
SELECT * FROM information_schema.columns
WHERE table_schema NOT IN ('pg_catalog', 'information_schema')
AND column_name='id_finish';
...which returns...
Array (
[table_catalog] => [database name]
[table_schema] => public
[table_name] => parts
[column_name] => id_metal
[ordinal_position] => 7
[column_default] =>
[is_nullable] => YES
[data_type] => bigint
[character_maximum_length] =>
[character_octet_length] =>
[numeric_precision] => 64
[numeric_precision_radix] => 2
[numeric_scale] => 0
[datetime_precision] =>
[interval_type] =>
[interval_precision] =>
[character_set_catalog] =>
[character_set_schema] =>
[character_set_name] =>
[collation_catalog] =>
[collation_schema] =>
[collation_name] =>
[domain_catalog] =>
[domain_schema] =>
[domain_name] =>
[udt_catalog] => [database name]
[udt_schema] => pg_catalog
[udt_name] => int8
[scope_catalog] =>
[scope_schema] =>
[scope_name] =>
[maximum_cardinality] =>
[dtd_identifier] => 7
[is_self_referencing] => NO
[is_identity] => NO
[identity_generation] =>
[identity_start] =>
[identity_increment] =>
[identity_maximum] =>
[identity_minimum] =>
[identity_cycle] =>
[is_generated] => NEVER
[generation_expression] =>
[is_updatable] => YES
)
You are going through a lot of hoops with permissions, but the problem is simple syntax:
WITH update_parts (id, id_finish) AS (
VALUES (1,42), (2,42), (3,30), (4,30)
)
UPDATE parts SET id_metal = up.id_finish
FROM update_parts up WHERE up.id = parts.id;
In your CTE you define the columns id and id_finish so your main query should refer to the same up.id_finish, not the id_metal from the parts table.
Further, it is usless to update parts.id with the value of update_parts.id because they are the same by definition: WHERE up.id = parts.id.

Role not found error

I'm trying to setup ZfcUser with BjyAuthorize. I'm getting the following error when trying to access the guarded route "/user".
Fatal error: Uncaught exception 'Zend\Permissions\Acl\Exception\InvalidArgumentException' with message 'Role '3' not found' in /home/brian/dev/ptapp/app/vendor/zendframework/zendframework/library/Zend/Permissions/Acl/Role/Registry.php:106
Stack trace:
#0 /home/brian/dev/ptapp/app/vendor/zendframework/zendframework/library/Zend/Permissions/Acl/Role/Registry.php(67): Zend\Permissions\Acl\Role\Registry->get('3')
#1 /home/brian/dev/ptapp/app/vendor/zendframework/zendframework/library/Zend/Permissions/Acl/Acl.php(112): Zend\Permissions\Acl\Role\Registry->add(Object(Zend\Permissions\Acl\Role\GenericRole), Array)
#2 /home/brian/dev/ptapp/app/vendor/bjyoungblood/bjy-authorize/src/BjyAuthorize/Service/Authorize.php(277): Zend\Permissions\Acl\Acl->addRole('bjyauthorize-id...', Array)
#3 /home/brian/dev/ptapp/app/vendor/bjyoungblood/bjy-authorize/src/BjyAuthorize/Service/Authorize.php(90): BjyAuthorize\Service\Authorize->load()
#4 /home/brian/dev/ptapp/app/vendor/bjyoungblood/bjy-authorize/src/BjyAuthorize/Service/Authorize.php(239) in /home/brian/dev/ptapp/app/vendor/zendframework/zendframework/library/Zend/Permissions/Acl/Role/Registry.php on line 69
My database tables were created with the provided schema.sql in the bjyauthorize repository, which contains the following code:
CREATE TABLE IF NOT EXISTS `user_role` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`roleId` varchar(255) NOT NULL,
`is_default` tinyint(1) NOT NULL,
`parent_id` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `user_role_linker` (
`user_id` int(11) unsigned NOT NULL,
`role_id` int(11) NOT NULL,
PRIMARY KEY (`user_id`,`role_id`),
KEY `role_id` (`role_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
;
With entries:
user_role
id | roleId | is_default | parent_id
---------------------------------------------
1 admin 0 therapist
2 therapist 0 patient
3 patient 0 user
4 guest 1 NULL
5 user 0 NULL
user_role_linker
user_id role_id
-------------------
3 3
I had to modify my bjyauthorize.global.php file because the "role_id_field" and the "parent_role_field" value didn't match up with sql schema provided. It looks like this:
<?php
return array(
'bjyauthorize' => array(
'default_role' => 'guest',
'identity_provider' => 'BjyAuthorize\Provider\Identity\ZfcUserZendDb',
'role_providers' => array(
'BjyAuthorize\Provider\Role\ZendDb' => array(
'table' => 'user_role',
'role_id_field' => 'roleId',
'parent_role_field' => 'parent_id',
),
),
'guards' => array(
'BjyAuthorize\Guard\Route' => array(
array('route' => 'zfcuser', 'roles' => array('user')),
array('route' => 'zfcuser/logout', 'roles' => array('user')),
array('route' => 'zfcuser/login', 'roles' => array('guest')),
array('route' => 'zfcuser/register', 'roles' => array('guest')),
// Below is the default index action used by the ZendSkeletonApplication
array('route' => 'home', 'roles' => array('guest', 'user')),
),
),
),
);
And my application.config.php looks like this:
<?php
return array(
'modules' => array(
'Application',
'ZfcBase',
'ZfcUser',
'User',
'BjyAuthorize',
),
'module_listener_options' => array(
'module_paths' => array(
'./module',
'./vendor',
),
'config_glob_paths' => array(
'config/autoload/{,*.}{global,local}.php',
),
),
);
Where the module "User" Is my custom ZfcUser Entity.
Any ideas where the problem is? I'm pretty new to ZF2 and zfc so thanks for your help!
EDIT: I should note that when I'm not logged in, I correctly get a 403 when trying to access /user, it's when I'm logged in that I receive this message. I receive it when trying to access any route (except invalid routes, I get a 404)
Based on first Comment, following sql works,
the same problem exists on parent_id, you need to change it, too:
CREATE TABLE IF NOT EXISTS `user_role` (
`id` INT(11) NOT NULL AUTO_INCREMENT,
`role_id` VARCHAR(255) NOT NULL,
`is_default` TINYINT(1) NOT NULL DEFAULT 0,
`parent_id` VARCHAR(255) NULL,
PRIMARY KEY (`id`),
UNIQUE INDEX `unique_role` (`role_id` ASC),
INDEX `idx_parent_id` (`parent_id` ASC),
CONSTRAINT `fk_parent_id` FOREIGN KEY (`parent_id`) REFERENCES `user_role` (`role_id`) ON DELETE SET NULL
) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 COLLATE = utf8_unicode_ci;
CREATE TABLE IF NOT EXISTS `user_role_linker` (
`user_id` INT UNSIGNED NOT NULL,
`role_id` VARCHAR(255) NOT NULL,
PRIMARY KEY (`user_id`, `role_id`),
INDEX `idx_role_id` (`role_id` ASC),
INDEX `idx_user_id` (`user_id` ASC),
CONSTRAINT `fk_role_id` FOREIGN KEY (`role_id`) REFERENCES `user_role` (`role_id`) ON DELETE CASCADE,
CONSTRAINT `fk_user_id` FOREIGN KEY (`user_id`) REFERENCES `user` (`user_id`) ON DELETE CASCADE
) ENGINE = InnoDB DEFAULT CHARACTER SET = utf8 COLLATE = utf8_unicode_ci;
The problem seems to be with the provided sql schema. In the user_role_linker table, change the role_id field to a VARCHAR. When making entries to this table, user_id should correspond to the user's numerical id, but the role_id should be the text id of the "roleId" field in the user_role table.

Zend Relationship - Two column referencing single field in other table

I have two tables with structure as mentioned below:
CREATE TABLE `up_offer` (
`up_offer_id` int(11) NOT NULL AUTO_INCREMENT,
`from_subscription_id` int(11) NOT NULL,
`to_subscription_id` int(11) NOT NULL,
PRIMARY KEY (`up_offer_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
CREATE TABLE `subscription` (
`subscription_id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(1000) NOT NULL,
`code` varchar(45) NOT NULL,
`price` decimal(6,2) NOT NULL,
`billing_cycle` int(11) NOT NULL,
`desc` varchar(2000) DEFAULT NULL,
`start_date` date NOT NULL,
`end_date` date NOT NULL,
`emaillist_id` int(11) NOT NULL,
`old_created_date` datetime NOT NULL,
`old_last_updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`created_on` datetime NOT NULL,
`last_updated_on` datetime NOT NULL,
`is_active` bit(1) NOT NULL DEFAULT b'1',
PRIMARY KEY (`subscription_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
The dbTable Class am using for both the tables is as follows:
class Admin_Model_DbTable_Subscription extends Zend_Db_Table_Abstract
{
protected $_name = 'subscription';
protected $_primary = 'subscription_id';
protected $_dependentTables = 'Admin_Model_DbTable_UpOffer';
protected $_referenceMap = array(
'UpOffer' => array(
'columns' => array('subscription_id'),
'refTableClass' => 'Admin_Model_DbTable_UpOffer',
'refColumns' => array('from_subscription_id','to_subscription_id'),
),
);
}
class Admin_Model_DbTable_UpOffer extends Zend_Db_Table_Abstract{
protected $_name = 'up_offer';
protected $_dependentTables = 'Admin_Model_DbTable_Offer';
protected $_referenceMap = array(
'Offer'=>array(
'columns' => 'up_offer_id',
'refTableClass' => 'Admin_Model_DbTable_Offer',
'refColumns' => 'up_offer_id'
)
);
}
I want to get the dependent data from the 'Zend_Db_Table_Row Object':
the code am writing is:
$upOfferData->toArray() gives the fields:
Array
(
[up_offer_id] => 1
[from_subscription_id] => 10
[to_subscription_id] => 9
)
And $upOfferData->findDependentRowset('Admin_Model_DbTable_Subscription'); gives output as follows:
Array
(
[0] => Array
(
[subscription_id] => 10
[name] => 001
[code] => 010
[price] => 10.00
[billing_cycle] => 1
[desc] => Test
[start_date] => 2012-04-21
[end_date] => 2012-05-20
[emaillist_id] => 0
[old_created_date] => 0000-00-00 00:00:00
[old_last_updated] => 2012-04-20 15:29:57
[created_on] => 2012-04-20 09:59:56
[last_updated_on] => 2012-04-20 01:31:44
[is_active] => 1
)
)
What about the to_subscription_id?
How do i correctly map the DbTable Classes and what is the correct way of obtaining the desired out?
The desired should be something like:
Array
(
[0] => Array
(
[subscription_id] => 10
[name] => 001
[code] => 010
[price] => 10.00
[billing_cycle] => 1
[desc] => Test
[start_date] => 2012-04-21
[end_date] => 2012-05-20
[emaillist_id] => 0
[old_created_date] => 0000-00-00 00:00:00
[old_last_updated] => 2012-04-20 15:29:57
[created_on] => 2012-04-20 09:59:56
[last_updated_on] => 2012-04-20 01:31:44
[is_active] => 1
)
[1] => Array
(
[subscription_id] => 9
[name] => 002
[code] => 011
[price] => 50.00
[billing_cycle] => 2
[desc] => Test
[start_date] => 2012-04-21
[end_date] => 2012-05-20
[emaillist_id] => 0
[old_created_date] => 0000-00-00 00:00:00
[old_last_updated] => 2012-04-20 15:29:57
[created_on] => 2012-04-20 09:59:56
[last_updated_on] => 2012-04-20 01:31:44
[is_active] => 1
)
)