EF code first schema generation problem - entity-framework-4.1

Why does this mapping (on SQL CE 4.0)
ToTable("USERS");
HasKey(c => c.Id);
Property(c => c.Id).HasColumnName("USERS_ID");
Property(c => c.ActiveDirectoryUsername).HasColumnName("AD_ID");
Property(c => c.LastUpdated).HasColumnName("LastUpdated").IsOptional();
Property(c => c.Active).HasColumnName("Active").IsOptional();
Property(c => c.AccountType).HasColumnName("AccountType").IsOptional();
HasOptional(c => c.Contact).WithMany().Map(c => c.MapKey("CONTACT_ID"));
Map<UserCompanyLink>(m => m.Requires("IsCompanyDelegate").HasValue(1));
Map<UserDirectorLink>(m => m.Requires("IsCompanyDelegate").HasValue(0));
Generate this error
SetUp : System.InvalidOperationException : The database creation succeeded, but the creation of the database objects did not. See inner exception for more details.
----> System.Data.SqlServerCe.SqlCeException : A column ID occurred more than once in the specification.
I would love to be able to see the schema sql being generated to debug this...
edit
Having added the IsCompanyDelegate to UserLink base entity, i now get
SetUp : System.Data.DataException : An exception occurred while initializing the database. See the InnerException for details.
----> System.Data.EntityCommandCompilationException : An error occurred while preparing the command definition. See the inner exception for details.
----> System.Data.MappingException :
(69,10) : error 3023: Problem in mapping fragments starting at lines 69, 79, 88, 172:Column UserLink.IsCompanyDelegate has no default value and is not nullable. A column value is required to store entity data.
An Entity with Key (PK) will not round-trip when:
((PK is NOT in 'UserLinks' EntitySet OR Entity is type [eServices.Admin.Data.Contexts.UserLink]) AND (PK is in 'UserLinks' EntitySet OR PK plays Role 'UserLink_Contact_Source' in AssociationSet 'UserLink_Contact'))
Utter cryptic gobbledygook.
Why is mapping TPH so damn complicated. the whole point of code first is to be able to create a model as you see fit?
edit
so it appears with no database existing, we get the first error (i.e. first test run), so the 2nd error is presumable irrelevant.

Turns out it was a random error not related to this particular relationship.
I changed the connection from SQL Server CE to SQL Server 2008, and I was given a much more useful error message. This time it told me which column ID was and on which table.
Moral of the story, if you are using SQL Server CE, try its bigger brother, you might have more luck.

Related

CakePHP 3.0: Mysql Syntax Error caused by a class named Group

I just created a table called group and generated the skeleton files referenced to this table.
I realized that this name enter in conflict with MySQL Reserved Words, because cakephp3.0 generates queries like that:
SELECT
Group.group_id AS `Group__group_id`,
Group.name AS `Group__name`,
Group.created_at AS `Group__created_at`
FROM
group Group
LIMIT
20 OFFSET 0
That throws this error:
Error: SQLSTATE[42000]: Syntax error or access violation: 1064 You
have an error in your SQL syntax; check the manual that corresponds to
your MySQL server version for the right syntax to use near 'group Group
LIMIT 20 OFFSET 0' at line 1
Is there a way to avoid this kind of error?
Indeed you can enable the quoteItendifiers but that comes with a performance hit as it says in the comment above it.
I use a different solution to this issue, by customizing the Table class for the problematic db_table like so:
Note the table alias being renamed and also the table name I have escaped manually
class GroupTable extends Table
{
public function initialize(array $config)
{
parent::initialize($config); // TODO: Change the autogenerated stub
$this->setAlias('MyGroup');
$this->setTable("`group`");
}
}
This will generate a query looking like this:
SELECT
MyGroup.id AS `MyGroup__id`,
MyGroup.filed1 AS `MyGroup__filed1`
FROM
`group` MyGroup
With CakePHP 3.6 $Group->find()->all() runs successfully.
I'm using CakePHP 4, and to solve this problem, I just added quoteIdentifiers => true, inside config -> app_local -> datasources
Datasources' => [
'default' => [
'quoteIdentifiers' => true,
'host' => '127.0.0.1',
quoteIdentifiers
Set to true if you are using reserved words or special characters in your table or column names. Enabling this setting will result in queries built using the Query Builder having identifiers quoted when creating SQL. It should be noted that this decreases performance because each query needs to be traversed and manipulated before being executed.
See more in: https://book.cakephp.org/4/en/orm/database-basics.html
I just found the solution. The solution is to change the value of 'quoteIdentifiers' to true in your Datasource configuration. May you need to clear the cache.
Source: https://book.cakephp.org/3.0/en/orm/database-basics.html#configuration

Unknown column 'Extent1.Discriminator' in 'where clause'

I am using Visual Studio 2013 web form application with MySql database to build a web form application but I have been unable to get past 'Membership and Role Management'.
I used a database first approach for the membership and when I try registering a new user, I get the error message below:
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: MySql.Data.MySqlClient.MySqlException: Unknown column 'Extent1.Discriminator' in 'where clause'
Source Error:
Line 16: var manager = new UserManager();
Line 17: var user = new ApplicationUser() { UserName = UserName.Text };
Line 18: IdentityResult result = manager.Create(user, Password.Text);
Line 19: if (result.Succeeded)
Line 20: {
Source File: c:\WebsiteProjects\ASPNETWebProjects\RevenuePortal\RevenuePortal\Account\Register.aspx.cs
Strangely, I do not have an 'Extent1.Discriminator' column anywhere in the database and cannot understand the reason for this frustrating error.
Extent1 is a table alias used by entity framework when it constructs the underlying sql statements. The error means that EF is either not configured correctly or misinterprets your database structure.
You need to analyise the underlying query it generates and determine why EF us3s a field it is not supposed to. Probably a relationship between 2 tables is incorrectly set up.
if possible try to do migration from beginning. from below execution in Nuget package manager:VS 2019 - Tools - NuGet Package Manager - Package Manager Console - run command Add-Migration DBInit - once done, run another command Update-Database.
Above solution is for code first approach.
I had same issue when I changed my system, After did migration it started working for me. Hope same will work for others. happy programming!!

ActiveRecord not behaving as I expect it

Ruby 2.0
Windows 8.1
Rails 4.1
MySQL2 gem
To avoid an error, I am using the following code to check for an existing payment, prior to creating a new payment record:
payment = {"organization_id" => organization_id,
"date" => row[1],
"amount" => row[2],
"description" => row[3]}
slug = "#{organization_id.to_s}_#{row[1].to_s}_#{row[2].to_s}_#{row[3]})
organization_payment = OrganizationPayment.where(:slug => slug)[0]
if !organization_payment
new_organization_payment = OrganizationPayment.create(payment)
end
Every once in a while, I am getting the following error:
Mysql2::Error at /process_uploaded_payments_data
Duplicate entry 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxx' for key 'index_organization_payments_on_slug'
I also have the following in my model:
validates_uniqueness_of :slug
Is there any reason why the entry causing the duplicate error would not have been caught by the code above? Any ideas?
Solution
I am still not certain what caused the problem, but I learned the hard way that validating uniqueness does not really work, if you also have a before_save call in your model that creates the slug in question. The workaround is an exception handler:
begin
new_organization_payment = OrganizationPayment.create(payment)
rescue ActiveRecord::RecordNotUnique
next
end
I don't know if this is your problem but a possible cause of this could be race condition -- when your code is running in a process it can be interrupted right after the if condition before it creates the new record.
Putting a unique constraint on the column in the database is a fine way of dealing with this problem, though. You can catch the exception and deal with it that way. You also don't have to manually check for the duplicity, you can use active record validations; fetching the entire record just to check if it exists is not the best practice anyway. More info:
http://apidock.com/rails/ActiveRecord/Validations/ClassMethods/validates_uniqueness_of

sqlalchemy throws a DataError 22001 using tg2 and pyodbc to write into SQL Server 2005

I'm using a reflected sqlalchemy mapped class into a SQL Server table.
I DBSession.add() instances of Activities class (the mapped class) with data I get from a different source.
and then I called transaction.commit() (since I'm calling from tg2 I can't use session.commit())
the error traceback:
DataError: (DataError) ('22001', '[22001] [Microsoft][ODBC SQL Server Driver][SQ
L Server]String or binary data would be truncated. (8152) (SQLExecDirectW); [010
00] [Microsoft][ODBC SQL Server Driver][SQL Server]The statement has been termin
ated. (3621)') u'INSERT INTO [NOAR_LOADEVENTS] ([EVENTCODE]) VALUES (?)' ((u'210
401',), (u'210402',), (u'210602',), (u'210603',), (u'000010',), (u'000102',), (u
'000206',), (u'000107',) ... displaying 10 of 49 total bound parameter sets ...
(u'211302',), (u'210403',))
be glad to any help about this since I'm clueless how to continue/debug this from here
edit: I had a suspicion that this has something to do with unicode so I changed the sqlalchemy column to unicode.
maybe the DataError is stuck somehow and I need to call a rollback, but I don't know hot to call a rollback in transaction in tg2
edit:the EVENTCODE column in the mssql is:datatype:PK,nvarchar(6), not null
hope this helps
another edit: the insert code (the relevant part)
event = #json with data
ac['EVENTCODE']=event.get('code')#for example u'210602' - from the failing data
...
...
e = Activities(**ac) # this is the class mapped with sqlalchemy to the NOAR_LOADEVENTS in sqlalchemy.
DBSession2.add(e)
transaction.commit()
solved. #beargle comment led me in the right direction. seems the problem strangly enough was trying to insert to nvarchar field with length of 6. seems that a unicode string with a length of 6 like: u'110110' would produce an error while a string '110110' passes fine. so i use
variable.encode('utf-8') and everything work.
what ever.
I jumped into this error and I solved it by changing the definition of a column (DB side) from NVARCHAR(100) to NVARCHAR(200).

Entity Framework persisted computed column woes

I recently updated a computed column to be persisted due to poor performance when querying it.
However now updates to child records throw this error
System.Data.SqlClient.SqlException
Internal Query Processor Error: The query processor could not produce a query plan. For more information, contact Customer Support Services.
Having an inner exception of
An error occurred while saving entities that do not expose foreign key properties for their relationships. The EntityEntries property will return null because a single entity cannot be identified as the source of the exception. Handling of exceptions while saving can be made easier by exposing foreign key properties in your entity types.
This happens with or without an index on the column.
FYI I have a configuration for the column thus:
Property(c => c.DisplayName).HasColumnName("DISPLAY_NM").HasDatabaseGeneratedOption(DatabaseGeneratedOption.Computed);
Any workaround?
edit
The child element statement is pretty irrelevant - but here it is. Imagine entities Order, Company (an Order must have a Company). I create an Order with an un-changed Company and its the Company entity with the computed column that is causing the problem - it works fine without the persistence on the computed column (as expected there's 1 insert statement on Order and 0 update statements on Company)
I think this is the solution but unsure how to do it in EF
I solved similar problem by adding ID of related entity as property (essentialy exposed FK value in table), and when creating record, if I only assign id of related object to exposed FK property, everything works, related object is not needed.
You can see sample of entity having both related object and its ID mapped using EF fluid mapping here:
public ThingMap()
{
this.Property(t => t.Name)
.IsRequired()
.IsMaxLength()
.IsUnicode();
//// Table mappings
this.ToTable("Things", "go");
this.Property(t => t.Name).HasColumnName("Name");
this.Property(t => t.TypeId).HasColumnName("Type_Id");
//// References
this.HasRequired(t => t.Type)
.WithMany(t => t.Things)
.HasForeignKey(t => t.TypeId);
}